问题是在键盘给出的输入字符串中找到最长的单词,程序运行良好,它找到了最长的单词,除了如果最长的单词在输入的最后(对于例如,Hello Classroom!)程序将返回 Hello 而不是 Classroom!我认为是因为 '\0'。
代码如下:
int main() {
string s;
string tmp_longest;
string longest;
getline(cin, s);
int size = s.length();
int full_counter = 0, no_space_counter = 0;
for (int i = 0; i < s.length(); i++) {
full_counter++;
if (s.at(i) != ' ') {
no_space_counter++;
tmp_longest += s.at(i);
}
else if (s.at(i) == ' ' || s.at(i) == '\0') { // i think that's the problem but cant figure it out
if (tmp_longest.length() > longest.length())
longest = tmp_longest;
tmp_longest = "";
}
}
cout << "Longest word: " << longest << endl;
cout << "Character of the word: " << longest.length() << endl;
cout << "String length: " << full_counter << endl;
cout << "String length (without spaces): " << no_space_counter << endl;;
}
每次 for 遇到空格时,我都会进行检查,因此我可以检查实际内存最长的单词和最后内存的单词。
这里有一些 img 可以更好地解释问题。
最佳答案
线
else if (s.at(i) == ' ' || s.at(i) == '\0')
没有意义,因为i
的最后一个值是s.length()-1
for循环结束后,需要重复这几行
if (tmp_longest.length() > longest.length())
longest = tmp_longest;
关于C++ 最长单词出现次数,出现 '\0' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47001944/