我正在自学C++。我编写了这个程序来计算字符串中的单词数。我知道这不是最好的方法,但这是我能想到的。
我正在使用空格来计算单词数。问题就在这里。
countWords(""); // ok, 'x.empty()' identifies it as an empty string.
countWords(" "); // 'x.empty()' fails, function returns 1.
p.s 我希望这个程序不计算“!”、“?”等符号。作为言语。这是我的代码:
#include <iostream>
#include <string>
int countWords(std::string x);
int main() {
std::cout << countWords("Hello world!");
}
int countWords(std::string x) {
if(x.empty()) return 0; // if the string is empty
int Num = 1;
for(unsigned int i = 0; i < x.size(); i++) {
// if there is a space in the start
if(x[0] == ' ') continue;
// second condition makes sure that i don't count 2 spaces as 2 words
else if(x[i] == ' ' && x[i - 1] != ' ') Num++;
}
return Num;
}
你的功能可以简化为:
int countWords(std::string x) {
int Num = 0;
char prev = ' ';
for(unsigned int i = 0; i < x.size(); i++) {
if(x[i] != ' ' && prev == ' ') Num++;
prev = x[i];
}
return Num;
}
这里有一个demo
编辑:跟进评论:
这是替换其他字符的简单方法' '
,认为可能有一个构建方法:
void replace(std::string &s, char replacer, std::set<char> &replacies)
{
for (int i=0; i < s.size(); i++)
if (replacies.count(s[i])) s[i] = replacer;
}
demo
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)