【问题标题】:C++ Program to print the longest word of the string?C ++程序打印字符串的最长单词?
【发布时间】:2016-06-14 08:28:31
【问题描述】:
    #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) "

【问题讨论】:

  • 你想输出最大长度的所有单词吗?
  • 是的,我希望我的程序打印字符串中所有最大长度的单词。
  • 你为什么要这样格式化你的代码?为什么在展示给其他人之前至少不整理一下?为什么您不至少在将其展示给其他人之前对其进行整理,以便他们可以帮助您修复它??
  • @PreferenceBean:因为那会花很长时间,而且无论如何你都会得到答案,而且因为现在阅读和写作已经成为消亡技能,所以看起来:(
  • @ChristianHackl:这就是为什么我希望像弗拉德这样的人不要回答这样的问题。

标签: c++ string


【解决方案1】:
#include<iostream>
using namespace std;
int main()
{
string str;
    getline(cin,str);
    cin.ignore();
    int len =str.length();`
    

    int current_len=0,max_len=0;
    int initial=0,start=0;
    int i=0;
    
    while(1)
    {
       if(i==len+2)
        {break;}

       if(str[i]==' '|| i==len+1)
       {
           
           if(current_len>max_len)
           {   
               initial=start;
               max_len=current_len;
           }
           current_len=0;
           start=i+1;
       }
       else
       {
       current_len++;
       }
       
       i++;
    }

    for (int i = 0; i < max_len; i++)
    {
        cout<<str[i+initial];
    }

      

    cout<<endl<<max_len<<endl;
    return 0 ;

}

【讨论】:

  • 当链接到您自己的网站或内容(或您附属的内容)时,您must disclose your affiliation in the answer 以免被视为垃圾邮件。根据 Stack Exchange 政策,在您的用户名中包含与 URL 相同的文本或在您的个人资料中提及它不被视为充分披露。
【解决方案2】:
#include <iostream>
using namespace std;

string longestWordInSentence(string str) {
    // algorithm to count the number of words in the above string literal/ sentence
    int words = 0;
    for (int i = 0; i < str.length(); i++) {
        if (str[i] == ' ') {
            words++;
        }
    }

    // incrementing the words variable by one as the above algorithm does not take into account the last word, so we are incrementing
    // it here manually just for the sake of cracking this problem
    words += 1;  // words = 5

    // words would be the size of the array during initialization since this array appends only the words of the above string
    // and not the spaces. So the size of the array would be equal to the number of words in the above sentence
    string strWords[words];

    // this algorithm appends individual words in the array strWords
    short counter = 0;
    for (short i = 0; i < str.length(); i++) {
        strWords[counter] += str[i];
        // incrementing the counter variable as the iterating variable i loops over a space character just so it does not count
        // the space as well and appends it in the array
        if (str[i] == ' ') {
            counter++;
        }
    }

    // algorithm to find the longest word in the strWords array
    int sizeArray = sizeof(strWords) / sizeof(strWords[0]);  // length of the strWords array

    int longest = strWords[0].length();  // intializing a variable and setting it to the length of the first word in the strWords array
    string longestWord = "";             // this will store the longest word in the above string

    for (int i = 0; i < sizeArray; i++) {  // looping over the strWords array
        if (strWords[i].length() > longest) {
            longest = strWords[i].length();
            longestWord = strWords[i];  // updating the value of the longestWord variable with every loop iteration if the length of the proceeding word is greater than the length of the preceeding word
        }
    }

    return longestWord;  // return the longest word
}

int main() {
    string x = "I love solving algorithms";
    cout << longestWordInSentence(x);
    return 0;
}

我已经非常详细地解释了代码的每一行。请参考每一行代码前面的cmets。这是一个通用的方法:

  1. 计算给定句子中的单词数
  2. 初始化一个字符串数组,并设置数组的大小等于句子中的单词数
  3. 将给定句子的单词附加到数组中
  4. 遍历数组并应用查找字符串中最长单词的算法。这类似于在整数数组中查找最长的整数。
  5. 返回最长的单词。

【讨论】:

  • 计算 sizeArray 的方式不正确,因为单词的大小不同。
  • @Ben_LCDB 你能确认一下吗? wordssizeArray 都计算出值 4。如果您认为我的方法有问题或效率不高,我总是愿意更正
  • 好吧,对不起,我说它不正确是错误的,因为对于所有字符串,sizeof() 返回 32(您可以在此处阅读:stackoverflow.com/a/3770817/6547518)。但我认为使用它是非常不可读的,特别是因为你有'words'变量已经包含你在上面所期望的值。
  • @Ben_LCDB 是的,这可能是一段多余的代码;不过,感谢您指出!
【解决方案3】:
#include<bits/stdc++.h>
using namespace std;
int main() 
{ 
    string s,a;
    char ch;
    int len,mlen=0;
    getline(cin,s);
    char* token=strtok(&s[0]," ");
    string r;
    while(token!=NULL)
    {
        r=token;
        len=r.size();
        if(mlen<len)
        {
            mlen=len;
            a=token;
        }
        token = strtok(NULL, " ");
    }
    cout<<a;
    return 0;
}

【讨论】:

  • 感谢您的贡献!我建议添加对您的代码如何工作的描述,以便访问者更容易理解它。
【解决方案4】:
#include <iostream>
#include <vector>
#include <string>

void LongestWord(std::string &str){
    std::string workingWord = "";
    std::string maxWord = "";

    for (int i = 0; i < str.size(); i++){
        if(str[i] != ' ')
            workingWord += str[i];
        else
            workingWord = "";
        if (workingWord.size() > maxWord.size())
            maxWord = workingWord;
    }

    std::cout << maxWord;
}

int main(){
    std::string str;
    std::cout << "Enter a string:";
    getline(std::cin, str);

    LongestWord(str);
    std::cout << std::endl;
    return 0;
}

来源:http://www.cplusplus.com/forum/beginner/31169/

【讨论】:

    【解决方案5】:

    这里的基本思想是将每个字符添加到临时(最初为空)字符串中,直到遇到空格。在每个空格实例中,将临时字符串的长度与“maxword”字符串的长度进行比较,如果发现它更长,则更新该长度。在继续输入字符串中的下一个字符之前,临时字符串被清空(使用 '\0' 重置为 null)。

    #include <iostream>
    #include <string>
    using namespace std;
    
    string LongestWord(string str) { 
      string tempstring;
      string maxword;
      int len = str.length();
    
      for (int i = 0; i<=len; i++) {
    
        if (tempstring.length()>maxword.length())
         {
          maxword=tempstring;
         }
        if (str[i]!=' ')
         {
        tempstring=tempstring+str[i];
         }
        else 
         {
         tempstring='\0';
         }
      }
      return maxword; 
    
    }
    
    int main() { 
    
      cout << LongestWord(gets(stdin));
      return 0;
    
    }  
    

    【讨论】:

      【解决方案6】:

      将整行拆分成一个字符串向量不是更容易吗?

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

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

      编辑:

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

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

      【讨论】:

      • 您的建议听起来很棒!太感谢了。其实我刚开始编程,如果你能告诉我如何实现你的建议,那将是一个很大的帮助。
      • 不想变得粗鲁,您已经拥有了自己动手所需的一切。特别是,如果您正在开始编程。我可以给你一些伪代码。
      • 一点也不粗鲁。你花时间帮助我真的很感激。你可以吗?请这样做,那很好。
      • 你去。那是程序员的目标是找到一种做事的方法(并查看文档,大量文档)。如果你自己做这些练习,将帮助你进步。祝你学习编程好运 ;)
      【解决方案7】:

      我最初的解决方案有一个错误:如果你输入两个长度为n 的单词和一个长度为n + k 的单词,那么它会输出这三个单词。

      你应该做一个单独的if条件来检查单词长度是否和以前一样,如果是,那么你可以附加"; "和另一个单词。


      这就是我要做的:
      1. if(counter &gt; max_word) 更改为if(counter &gt;= max_word),这样同样长度的单词也会被考虑在内。
      2. 默认使用max 字符串(所以"" 而不是" ")。 (见下一点)
      3. if(counter &gt;= max_word)second if条件中添加if条件,查看max字符串是否为空,如果不为空则追加"; "
      4. max = 更改为 max += 以便它附加单词(在第二个条件中)

      【讨论】:

      • 非常感谢!但恐怕我没有完全理解你的观点 3。我是编程新手。你能告诉我 if 条件到底是什么吗?
      • @Kana_chan 在std::string中有一个empty()方法,如果字符串为空则返回true。因此,if 表达式将是if (!max.empty(),基本上是说“如果 max 不为空,则执行 ...”。要将字符串附加到字符串,只需使用str.append("something")。祝你好运:)
      • 我会试试这个。再次感谢!
      • @Kana_chan 我发布的“代码”包含一个错误,请查看我的编辑。
      【解决方案8】:

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

      #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
      

      【讨论】:

      • 正是我想要的输出。太感谢了!您能否简单介绍一下您所做的更改以及原因?我刚开始编程。非常感谢。
      • @Kana_chan 我正在使用标准字符串流从原始字符串中读取每个单词。
      • 好的。所以你基本上是将每个单词放入一个新字符串中?
      • @Kana_chan 注意std::istringstream is( s ); Vlad 将输入字符串放入另一个流中,他可以逐字解析。然后他只是查看每个单词的大小并记录到该点看到的最大大小和单词。 Documentation on stringstream
      • 非常感谢!来自莫斯科的@Vlad
      猜你喜欢
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多