用一个函数来实现将一行字符串中最长的单词输出。此行字符串从主函数传递给该函数。用c++来写这个题的代码
时间: 2024-02-19 09:01:25 浏览: 148
输出最长单词.c
以下是一个用C++编写的将一行字符串中最长的单词输出的程序:
```c++
#include <iostream>
#include <string>
using namespace std;
string longestWord(string str) {
string result = "";
int maxLength = 0;
string currentWord = "";
for (int i = 0; i < str.length(); i++) {
if (str[i] == ' ') {
if (currentWord.length() > maxLength) {
maxLength = currentWord.length();
result = currentWord;
}
currentWord = "";
} else {
currentWord += str[i];
}
}
if (currentWord.length() > maxLength) {
maxLength = currentWord.length();
result = currentWord;
}
return result;
}
int main() {
string str;
cout << "请输入一行字符串: ";
getline(cin, str);
string longest = longestWord(str);
cout << "最长的单词是: " << longest << endl;
return 0;
}
```
这个程序先从主函数中获取一行字符串,然后遍历字符串中的每个字符,以空格为分隔符将每个单词分开,并记录下最长的单词。如果你希望了解更多细节,可以参考这个链接:https://www.geeksforgeeks.org/find-the-longest-word-in-a-string/
阅读全文