帮我写一个c++函数,统计并输出一句话中最长的单词
时间: 2024-02-21 17:57:26 浏览: 101
好的,以下是一个简单的 C++ 函数,可以统计并输出一句话中最长的单词:
```c++
#include <iostream>
#include <string>
using namespace std;
string findLongestWord(string sentence) {
string longestWord = "";
string currentWord = "";
for (int i = 0; i < sentence.length(); i++) {
if (sentence[i] == ' ') {
if (currentWord.length() > longestWord.length()) {
longestWord = currentWord;
}
currentWord = "";
} else {
currentWord += sentence[i];
}
}
if (currentWord.length() > longestWord.length()) {
longestWord = currentWord;
}
return longestWord;
}
int main() {
string sentence = "The quick brown fox jumps over the lazy dog";
string longestWord = findLongestWord(sentence);
cout << "The longest word in the sentence is: " << longestWord << endl;
return 0;
}
```
这个函数接受一个字符串参数,表示要处理的句子。它会遍历整个句子,将每个单词存储在一个字符串变量中,并比较每个单词的长度,最终返回最长的单词。在主函数中,我们可以将句子传递给该函数并输出结果。
阅读全文