字符串中统计单词个数的两种做法
As a technology, “HailStorm” is so new that it is still only known by its code name.
逗号和句号这种标点符号,默认与上一个单词之间无空格。
1.用stringstream做
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string str,s1;
getline(cin, str);
stringstream is(str); //stringstream常用来字符串拼接和数据类型转换
int i = 0;
while (is>>s1)
{
i++;
}
printf(“单词数为:%d\n”, i);
}
2.传统做法
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int i = 0, j, count = 0;
getline(cin,str);
while (str[i++] != ‘\0’)
{
if (str[i] == ’ ')
{
i++;
while (str[i] == ’ ')//空格连续
{
i++;
}
count++;
}
}
printf(“单词数为:%d\n”, count + 1);
}
————————————————
版权声明:本文为CSDN博主「快送我回院里」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_42480530/article/details/114298280