C++ Program To Find Largest Word In A String(Sentence)

 

string example, c++ example, c++ program for practice,

Program:

#include <iostream>
#include <string.h>
using namespace std;

string findLargest(string str)
{
    string largestWord = "";
    string word = "";

    for(int i = 0; i < str.size(); i++)
    {
        if(str[i] == ' ')
        {
            //using ternary operator to get the largest size word
            largestWord = (largestWord.size() > word.size()) ? largestWord : word;
            word = "";
        }

        else
        word += str[i];
    }
    return largestWord;
}

int main()
{
    string str;

    cout << "Enter sentence: ";
    getline(cin,str);       //getting sentence from user

    cout << findLargest(str);

    return 0;
}

Output:

Enter sentence: Largest word in this sentence is
sentence
Learn more about string and see more string example.
C++ Program To Find Largest Word In A String(Sentence) C++ Program To Find Largest Word In A String(Sentence) Reviewed by Beast Coder on April 20, 2021 Rating: 5

No comments:

Powered by Blogger.