21xrx.com
2024-09-20 05:44:27 Friday
登录
文章检索 我的文章 写文章
C++:查找字符串中最长的单词并输出
2023-06-28 10:45:12 深夜i     --     --
C++ 字符串 最长单词 输出

C++是一门广泛使用的编程语言,它提供了许多有用的工具和函数,用于解决各种编程问题。在C++中,查找字符串中最长的单词并输出也是非常常见的问题。

首先,我们需要定义一个字符串,然后通过字符串分割函数将字符串分割成单词。一般情况下,我们可以使用空格作为分割符号。


string s = "hello world";

istringstream iss(s);

vector<string> words;

string word;

while (iss >> word) {

  words.push_back(word);

}

然后,我们可以循环遍历所有的单词,并找到其中最长的一个。


string longestWord = "";

for (string word : words) {

  if (word.length() > longestWord.length())

    longestWord = word;

  

}

cout << longestWord << endl;

最后,我们可以使用cout语句将最长的单词输出到控制台上。

完整的代码如下:


#include <iostream>

#include <sstream>

#include <vector>

using namespace std;

int main() {

  string s = "hello world";

  istringstream iss(s);

  vector<string> words;

  string word;

  while (iss >> word) {

    words.push_back(word);

  }

  string longestWord = "";

  for (string word : words) {

    if (word.length() > longestWord.length())

      longestWord = word;

    

  }

  cout << longestWord << endl;

  return 0;

}

可以看到,使用C++查找字符串中最长的单词并输出非常简单,并且可以通过各种方式进行优化和改进。无论是用于编程比赛还是实际开发中,这个问题都是非常有用和重要的。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复