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

时间:2016-03-01 18:55:07

标签: c++ string

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

当前的输出是&#39; 4这个&#39;在输入字符串&#34;这很酷&#34;。 我怎样才能打印出来#4; 4;酷&#39; ? 在通过终端在Linux中运行它时,它给了我错误 &#34;在抛出&#39; std :: out_of_range&#39;的实例后终止调用what():basic_string :: substr Aborted(core dumped)&#34;

6 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

#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 :(得分:0)

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

你应该制作一个单独的if条件来检查单词长度是否与之前相同,如果是,那么你可以追加"; "和另一个单词。

<小时/> 这就是我要做的事:

  1. if(counter > max_word)更改为if(counter >= max_word),因此也会考虑相同长度的字词。
  2. 默认设置max字符串(因此""代替" ")。 (见下一点)
  3. if(counter >= max_word)秒if条件中添加if条件以查看max字符串是否为空,如果它不为空,则追加"; " < / LI>
  4. max =更改为max +=,以便附加单词(在第二个条件中)

答案 3 :(得分:0)

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

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

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

编辑:

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

查看以下网站,了解有关矢量的所有参考资料。别忘了#include www.cplusplus.com/reference/vector/vector /

答案 4 :(得分:0)

#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 :(得分:0)

#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;
}
相关问题