1.题目描述
统计一串字符串中的字符数,字符串中可能包含大、小写英文字母、数字字符、空格和换行符。
统计字符数时,空格和换行符不计算在内。
2.输入输出格式
- 输入
输入一行字符串。
- 输出
输出一个整数,该整数是输入字符串的字符数(不包括空格和换行符)。
例如:
//输入
Learning is the enterprise of a lifetime
//输出
34
3.解题思路
在读入字符串时如果使用 cin 就会无法读入空格,因为 cin 读入空格后会认为字符串读入操作已经结束,所以这里使用 getline 读入带空格的字符串。然后利用字符串的 size()来求出字符串长度,接着使用 for 循环遍历字符串统计非空格的字符数。
//getline 的用法
//通过 cin 输入的字符串会被保存到str中
string str;
getline(cin,str);
//将字符串转化为数字 stoi只能处理 int
int n = stoi(str);
//将数字转化为字符串
string t = to_string(n);
#include <bits/stdc++.h>
using namespace std;
int main() {
string str;
getline(cin,str);
int count = 0;
int s = str.size();
for (int i = 0; i < s; i++) {
if (str[i] != ' ') {
count += 1;
}
else { continue; }
}
cout << count << endl;
return 0;
}
4.运行结果
5.题目升级
假设输入的字符串中存在非空格字符之间有多个空格的情况,需要输出非空格字符且每个非空格字符之间保留一个空格字符。
解法一:
使用 if 判断遍历的每个字符,若当前字符非空格,则读入输出;若当前字符为空格,同时该字符的下一个字符不为空格,则也读入输出。
#include <bits/stdc++.h>
using namespace std;
int main() {
string str;
getline(cin,str);
int s = str.size();
for (int i = 0; i < s; i++) {
if (str[i] != ' ' || str[i] == ' ' && str[i + 1] != ' ') {
cout << str[i];}
}
return 0;
}
运行效果:
解法二:
利用 cin 不能读入空格的特性,结合 while 循环读入,可以巧妙地忽略空格。
#include <bits/stdc++.h>
using namespace std;
int main() {
string str;
while (cin >> str) {
cout << str <<' ';
}
return 0;
}
运行效果:
最后使用 ctrl+z+回车退出程序。
6.细节问题
cin 和 getline 的区别
- cin: cin 通常用于读取基本数据类型,如整数、浮点数和字符等,它会忽略输入缓冲区中的空白字符(如空格、制表符和换行符)并将其留在缓冲区中。
- getline: getline 用于读取一行文本,包括空格和其他特殊字符,直到遇到换行符或文件结尾。getline 会将输入缓冲区中的所有内容都读取完毕,包括换行符和空格。
因此,如果想在使用 getline 之前调用 cin 来读取某个数据,需要在这两个函数之间清空输入缓冲区(例如通过调用 cin.ignore()函数),以免影响 getline 的结果。
例子:
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::cout << "Hello World!\n";
int a;
cin >> a;
cout << a << endl;
cin.ignore();
string s;
getline(cin, s);
cout << s << endl;
return 0;
}
如果不使用 cin.ignore() 的话,cin 会剩一个换行符, getline 会把这个换行符读进来,直接结束字符串读入。