凯刚写了一篇美妙的作文,请问这篇作文的标题中有多少个字符?
注意:标题中可能包含大、小写英文字母数符 可能包含大、小写英文字母数符可能包含大、小写英文字母数符可能包含大、小写英文字母数符 、空格和换行符 。统计标题字。统计标题字符数时,空格和换行符不计算在内。
输入描述:
输入文件只有一行, 一个字符串s。
输出描述:
输出文件只有一行,包含一个整数,即作文标题的字符数(不含空格和换行符)。
示例1
输入
234
输出
3
说明
标题中共有 3 个字符,这 3 个字符都是数字字符。
示例2
输入
Ca 45
输出
4
说明
标题中共有 5 个字符,包括 1 个大写英文字母,1 个小写英文字母和 2 个数字字符,
还有 1 个空格。由于空格不计入结果中,故标题的有效字符数为 4 个。
备注:
规定|s|表示字符串s的长度(即字符串中的字符串中的字符和空格数)。
对于40%的数据,1≤|s|≤5,保证输入为数字符及行末换符。
对于80%的数据,1≤|s|≤5,输入只可能包含大、小写英文字母大、小写英文字母、数字符及行末换符。
对于100%的数据,1≤|s|≤5,输入可能包含大,输入可能包含大、小写英文字母写英文字母、数字符、空格和行末换符。
代码一:最易想到的代码
#include <cstdio>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
string str;
int main()
{
getline(cin,str);
int res = 0;
for(int i = 0; i < str.size(); i++)
{
if(str[i] >= '0' && str[i] <= '9')
res++;
else if(str[i] >= 'a' && str[i] <= 'z')
res++;
else if(str[i] >= 'A' && str[i] <= 'Z')
res++;
}
cout<<res<<endl;
return 0;
}
代码二:
注意:cin 接受不了空格和换行符,必须用scanf
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
int main()
{
//第二种
char c;
int res = 0;
while(1)
{
//cin>>c; //cin读入char类型,会忽略空格,换行
scanf("%c",&c);
if(c == '\n') break;
if(c == ' ') continue;
res ++;
}
cout<<res<<endl;
return 0;
}
代码三:cin 输入忽略空格和换行,所以可以直接统计。
注意:要想退出循环,需要按 Ctrl + Z 键,再按回车,这是文件结束符。。
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
int main()
{
char c;
int s = 0;
while (cin >> c) s++;
cout << s << endl;
return 0;
}