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

C++ Program to print the longest word of the string?

本文关键字:单词 字符串 程序 打印 C++      更新时间:2023-10-16
    #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;
}

输入字符串"这很酷"时,当前输出为"4 This"。我如何让它打印'4 这个;酷'?通过终端在 Linux 中运行它时,它给了我错误" 终止在抛出 'std::out_of_range' 的实例后调用 what(): basic_string::substr 中止 (核心转储) "

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

#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

这里的基本思想是将每个字符添加到临时(最初为空)字符串中,直到遇到空格。在空间的每个实例中,将临时字符串的长度与"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='';
     }
  }
  return maxword; 
}
int main() { 
  cout << LongestWord(gets(stdin));
  return 0;
}  
#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;
}

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

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

我最初的解决方案包含一个错误:如果您要输入 2 个长度n单词和 1 个长度n + k单词,那么它将输出这三个单词。

您应该制作一个单独的 if 条件来检查单词长度是否与以前相同,如果是,则可以附加 "; " 和其他单词。


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

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

然后,

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

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

编辑:

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

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

#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/

#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;
}
#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 ;
}