//字符串
AcWing 760. 字符串长度
给定一行长度不超过 100 的非空字符串,请你求出它的具体长度。
输入格式
输入一行,表示一个字符串。注意字符串中可能包含空格。
输出格式
输出一个整数,表示它的长度。
字符串末尾无回车
输入样例:
I love Beijing.
输出样例:
15
思路:直接用getline()读入字符串,后用s.size()计算字符串长度
方案1:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
getline(cin,s);
cout<<s.size()<<endl;
return 0;
}
方案2:
(fgets函数会把回车也读进来)
#include<bits/stdc++.h>
using namespace std;
int main()
{
char s[105];
int c = 0;
fgets(s , 105 , stdin);
for(int i = 0;s[i] && s[i] != '\n';i ++) c ++;
cout << c << endl;
return 0;
}
761. 字符串中的数字个数
输入一行字符,长度不超过100,请你统计一下其中的数字字符的个数。
输入格式
输入一行字符。注意其中可能包含空格。
输出格式
输出一个整数,表示字数字字符的个数。
输入样例:
I am 18 years old this year.
输出样例:
2
解法1:常规套路,遍历一遍整个序列,判断是否有数字
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
int cnt = 0,T;
getline(cin,s);
for(int i = 0;i < s.size();i++)
{
if(s[i] >='0' && s[i] <='9')
{
cnt++;
}
}
cout<<cnt;
return 0;
}
解法2:
思路:用isdigit()判断
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
int cnt = 0;
getline(cin, s);
for(char c:s)//复制一个s字符串再进行遍历操作,但是复制一个字符串需要花费大量的时间,支持C++11
{
if(isdigit(c))
{
cnt++;
}
}
cout<<cnt;
return 0;
}
这道题还可以运用auto