c++shortest

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


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

Solution

  • void ShortestWord(string text)
    {
    string tmpWord = "";
    // The upper bound of answer is text
    string minWord = text;
    
    for(int i=0; i < (int)text.length(); i++)
    {
        /// If founded space, rewrite word
    
        if(text[i] != ' ')
        {
            tmpWord += text[i];
        }
        else
        {
            // We got a new word, try to update answer
            if(tmpWord.length() < minWord.length())
                minWord=tmpWord;
            tmpWord = "";
        }
    
    }
    // Check the last word
    if(tmpWord != "")
    {
        if(tmpWord.length() < minWord.length())
            minWord=tmpWord;
    }
    cout << "Shortest Word: " << minWord << endl;
    cout << "Word Length: " << minWord.length() << endl;
    }