C程序打印字符串的最长单词?

新手上路,请多包涵
    #include <iostream>
#include <string>

using namespace std;

int main()
{
string s;
getline(cin , s) ; #input of string from user
int counter = 0;
int max_word = -1;
int len = s.length(); #length of string
string max = " ";
string counter_word = " ";

for (int i = 0; i < len; i++)
{
    if(s[i] != ' ')
        {
        counter++;
        }

    if(s[i] == ' ' || i == len - 1)
    {
        if(counter > max_word)
            {
            max_word = counter;
                        //handling end of string.
            if(i == len - 1)
                            max = s.substr(i + 1 - max_word, max_word); #sub string command that prints the longest word
                        else
                max = s.substr(i - max_word, max_word);
                }

    counter = 0;
    }
}
cout << max_word << " " << max << endl; #output
return 0;
}

输入字符串“This is cool”时,当前输出为“4 This”。如何让它打印 ‘4 This;凉爽的’ ?在通过终端在 Linux 中运行它时,它给了我错误“在抛出 ‘std::out_of_range’ what(): basic_string::substr Aborted (core dumped) 的实例后调用终止”

原文由 Kana_chan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 285
2 个回答

如果我对您的理解正确,那么您的意思是以下

#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::string s;

    std::getline( std::cin, s );

    std::string::size_type max_size;
    std::string max_word;
    std::string word;

    std::istringstream is( s );
    max_size = 0;
    while ( is >> word )
    {
        if ( max_size < word.size() )
        {
            max_size = word.size();
            max_word = word;
        }
        else if ( max_size == word.size() )
        {
            max_word += "; ";
            max_word += word;
        }
    }

    std::cout << max_size << ' ' << max_word << std::endl;
}

如果输入字符串

This is cool

那么输出将是

4 This; cool

原文由 Vlad from Moscow 发布,翻译遵循 CC BY-SA 3.0 许可协议

将整行拆分为 string 向量不是更容易吗?

然后你可以询问字符串中每个元素的长度,然后打印出来。因为现在您仍然将所有单词放在一个字符串中,这使得每个单词都难以分析。

如果您使用单个字符串,也很难按照您的要求打印具有相同长度的所有单词。

编辑 :

  • 首先循环遍历整个输入
    • 在当前单词和之前保存的单词之间保持较大的单词长度
    • 为每个单词创建一个子字符串并将其 push_back 转换为向量
  • 打印大字的长度
  • 循环遍历向量并打印该大小的每个单词。

查看以下网站以获取有关矢量的所有参考资料。不要忘记#include www.cplusplus.com/reference/vector/vector/

原文由 Karlyr 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题