How to find the shortest word in the string C++

user6275758 picture user6275758 · Apr 30, 2016 · Viewed 7.6k times · Source

I need a help. I have a function which print Longest Word in sentence. But how to display shortest word?

string text = "My name is Bob";

void LongestWord(string text)
{
string tmpWord = "";
string maxWord = "";

for(int i=0; i < text.length(); i++)
{
    /// If founded space, rewrite word
    if(text[i] != ' ')
        tmpWord += text[i];
    else
        tmpWord = "";
    /// All the time check word length and if tmpWord > maxWord => Rewrite.
    if(tmpWord.length() > maxWord.length())
        maxWord=tmpWord;
}
cout << "Longest Word: " << maxWord << endl;
cout << "Word Length: " << maxWord.length() << endl;
}

Answer

Biruk Abebe picture Biruk Abebe · Apr 30, 2016

The suggestion given in the comment section will work, it's just a matter of rearranging your control structures to make it work. i.e

for(int i=0; i < text.length(); i++)
{
    /// If founded space, rewrite word
    if(text[i] != ' ')
        tmpWord += text[i];
    else
    {
       if(minWord.length()==0)//this only happens once
              minWord=tmpWord;//for the first word,you need to assign minWord so you have something to compare to

       if(tmpWord.length() < minWord.length() )//move this block here
            minWord=tmpWord;

       tmpWord = "";
    }

}

I might add, you can check for a word much easily if you used istringstream with the extraction operator>>. Something like:

    #include <sstream>
    ....

    string text="my name is bob";
    string tmpWord = "";
    string minWord = "";
    istringstream ss(text);//defines the input string stream and sets text in the input stream buffer

    while(ss.peek()!=EOF)//until the end of the stream
    {
        ss>>tmpWord;//read a word up to a space

       if(minWord.length()==0)//this only happens once
              minWord=tmpWord;

       if(tmpWord.length() < minWord.length() )
            minWord=tmpWord;

    }