『题解』洛谷P5015 标题统计

题意描述

给你一个字符串,求所有字符的总数。

字符只包含数字,大小写字母。

分析

字符串的长度还是(le5)的。

直接枚举就可以了。

AC代码:

NOIP官方标准程序是这样的
#include <iostream>
#include <cstdlib>
#include <string>

int main() {
    freopen("title.in", "r", stdin);
    freopen("title.out", "w", stdout);

    std::string s;
    std::getline(std::cin, s);
    int cnt = 0;
    if (s.length() > 0 && s[0] != ' ') ++cnt;
    if (s.length() > 1 && s[1] != ' ') ++cnt;
    if (s.length() > 2 && s[2] != ' ') ++cnt;
    if (s.length() > 3 && s[3] != ' ') ++cnt;
    if (s.length() > 4 && s[4] != ' ') ++cnt;
    std::cout << cnt << std::endl;

    return 0;
}

直接枚举(5)个位。

还是我的比较可观:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>

using namespace std;

char s[10];
int main() {
    gets(s);//读入字符串(不推荐用,再Linux下的换行符和Windows下的不一样)
    int ans=0;//清空ans
    for (int i=0; i<strlen(s); i++) {//别忘了C++字符串下标是从0开始的
        if (s[i]>='A' &&s[i]<='Z') ans++;
        if (s[i]>='a' &&s[i]<='z') ans++;
        if (s[i]>='0' &&s[i]<='9') ans++;//数字
    }
    printf("%d
",ans);//输出结果
    return 0;
}
原文地址:https://www.cnblogs.com/shenxiaohuang/p/10162159.html