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

The current output is '4 This' on entering the string "This is cool". How do I get it to print '4 This; Cool' ? On running it in Linux through the terminal, it gives me the error " terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr Aborted (core dumped) "

Kana_chan
  • 23
  • 1
  • 1
  • 6
  • Do you want to output all words wuth the maximum length? – Vlad from Moscow Mar 01 '16 at 19:06
  • Yes, I would like my program to print all the words with the maximum length in the string. – Kana_chan Mar 01 '16 at 19:15
  • 1
    Why would you format your code like this? Why would you not at least tidy it up before showing it to other human beings? Why would you not _at least_ tidy it up before showing it to other human beings so they can help you fix it?? – Lightness Races in Orbit Mar 01 '16 at 20:11
  • @PreferenceBean: Because that would take too long, and you get an answer anyway, and because reading and writing are dying skills these days, it seems :( – Christian Hackl Mar 01 '16 at 20:25
  • @ChristianHackl: This is why I wish people like Vlad wouldn't answer questions like this. – Lightness Races in Orbit Mar 01 '16 at 20:26
  • @Kana_chan You may benefit from reading a C++ style guide ([this one](https://google.github.io/styleguide/cppguide.html) is google's). And by looking over code formatting on SO [here](http://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks). – franklin Mar 01 '16 at 21:00
  • Thank you @franklin for helping me out :) I'll check that out – Kana_chan Mar 02 '16 at 13:22

8 Answers8

3

If I have understood you correctly then you mean the following

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

If to enter string

This is cool

then the output will be

4 This; cool
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Precisely what I wanted my output to be. Thank you so much! Could you just brief me about what changes you made and why? I just started programming. Thanks a lot. – Kana_chan Mar 01 '16 at 19:22
  • @Kana_chan I am using the standard string stream that to read each word from the original string. – Vlad from Moscow Mar 01 '16 at 19:24
  • Alright. So you're basically putting each word into a new string? – Kana_chan Mar 01 '16 at 19:29
  • @Kana_chan Note `std::istringstream is( s );` Vlad takes the input string and places it into another stream that he can parse word-by-word. Then he just looks at the size of each word and records the largest size and word seen to that point. [Documentation on stringstream](http://en.cppreference.com/w/cpp/io/basic_stringstream) – user4581301 Mar 01 '16 at 19:41
  • Thank you so much! @Vlad from Moscow – Kana_chan Mar 01 '16 at 20:00
2

The basic idea here is to add each character to a temporary (initially empty) string until a space is encountered. At each instance of a space, the length of the temporary string is compared to the length of the "maxword" string, which is updated if it is found to be longer. The temporary string is emptied (reset to null using '\0') before proceeding to the next character in the input string.

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

}  
bloodrootfc
  • 1,133
  • 12
  • 10
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;
}

I have explained every line of the code in great detail. Please refer to the comments in front of every line of code. Here is a generalized approach:

  1. Count the number of words in the given sentence
  2. Initialize a string array and set the size of the array equal to the number of words in the sentence
  3. Append the words of the given sentence to the array
  4. Loop through the array and apply the algorithm of finding the longest word in the string. It is similar to finding the longest integer in an array of integers.
  5. Return the longest word.
  • The way you compute sizeArray isn't correct because words have different size. –  Jun 22 '21 at 20:14
  • @Ben_LCDB Could you please confirm this? Both `words` and `sizeArray` compute the value 4. If you think, something is wrong with my approach or it isn't efficient, I'm always open to corrections – Harris Ahmad Jun 22 '21 at 20:41
  • ok sorry I was wrong to say that it is incorrect because for all string, sizeof() return 32 (as you can read here: https://stackoverflow.com/a/3770817/6547518). But i think that this is quite unreadable to use this, especially since you have the 'words' variable that already contains the value that you expect just above. –  Jun 22 '21 at 22:34
  • 1
    @Ben_LCDB Yeah, that might be a redundant piece of code; thanks for pointing it out, though! – Harris Ahmad Jun 23 '21 at 00:06
0

My original solution contained a bug: If you were to input 2 words of length n and 1 word of length n + k, then it would output those three words.

You should make a separate if condition to check whether the word length is the same as before, if yes, then you can append "; " and the other word.


This is what I would do:
  1. Change if(counter > max_word) to if(counter >= max_word) so words of the same length are also taken into account.
  2. Make the max string by default (so "" instead of " "). (See next point)
  3. Add an if condition in the if(counter >= max_word)second if condition to see if the max string is not empty, and if it's not empty append "; "
  4. Changing max = to max += so that it appends the words (in the second condition)
Rakete1111
  • 47,013
  • 16
  • 123
  • 162
  • Thank you so much! But I'm afraid I didn't exactly get your point 3. I'm new to programming. Could you please tell me what the if condition would exactly be? – Kana_chan Mar 01 '16 at 19:20
  • @Kana_chan There is a `empty()` method in `std::string`, which returns true if the string is empty. So by consequence the if expression would be `if (!max.empty()`, basically saying "if max not empty then do ...". To append a string to a string just use `str.append("something")`. Good luck :) – Rakete1111 Mar 01 '16 at 19:33
  • I'll try this. Thanks again! – Kana_chan Mar 01 '16 at 19:40
  • @Kana_chan The "code" I posted contains a bug, see my edit please. – Rakete1111 Mar 01 '16 at 19:44
0

Wouldn't it be easier for you to split the whole line into a vector of string ?

Then you could ask the length of each element of the string and then print them. Because right now you still have all the words in a single string making each individual word hard to analyse.

It would also be hard, as you requested, to print all the words with the same length if you use a single string.

EDIT :

  • Start by looping through your whole input
    • Keep the greater length of word between the current one and the previously saved
    • Make a substring for each word and push_back it into a vector
  • Print the length of the bigger word
  • Loop through the vector and print each word of that size.

Look the following website for all references about vectors. dont forget to #include www.cplusplus.com/reference/vector/vector/

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Karlyr
  • 123
  • 9
  • Your suggestion sounds great! Thank you so much. Actually I just started programming, it would be a great help if you could tell me how to implement your suggestion. – Kana_chan Mar 01 '16 at 19:16
  • Without wanting to be rude, you already have all you need to do it yourself. Especially, if you are starting programming. I can give you some pseudo-code. – Karlyr Mar 01 '16 at 19:33
  • Not rude at all. You taking time to help me out is really appreciated. Can you? Please do, that'd be nice. – Kana_chan Mar 01 '16 at 19:39
  • There you go. That's the goal of a programmer to find a way to do things (and look through documentation, lots of documentation). These kind of exercise will help you progress if you do them yourself. Good luck on learning to program ;) – Karlyr Mar 01 '16 at 19:43
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;
}

Source: http://www.cplusplus.com/forum/beginner/31169/

Testing123
  • 363
  • 2
  • 12
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;
}
roschach
  • 8,390
  • 14
  • 74
  • 124
  • Thanks for your contribution! I would recommend adding a description of how your code works so that it's easier for visitors to understand it. – apetranzilla Feb 27 '19 at 18:26
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 ;

}
JensB
  • 839
  • 4
  • 19
  • 1
    When linking to your own site or content (or content that you are affiliated with), you [must disclose your affiliation _in the answer_](/help/promotion) in order for it not to be considered spam. Having the same text in your username as the URL or mentioning it in your profile is not considered sufficient disclosure under Stack Exchange policy. – cigien Dec 11 '21 at 16:29