C++ Programming

Write a C++ program to find the largest word in a given string.

Method 1

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main() {
  string str, word, largestWord;
  int maxLength = 0;
  cout << "Enter any sequence of words or line: ";
  getline(cin, str);
  //Break a string into words
  stringstream strStream(str);
  while (strStream >> word) {
    if (word.length() > maxLength) {
      maxLength = word.length();
      largestWord = word;
    }
  }
  //Print the output
  cout << "Largest word: " << largestWord << endl;
  return 0;
}
	

Output

Enter any sequence of words or line: CodeDesire is about programming and technology 
Largest word: programming

Method 2

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

    string SearchLargestWord(const string& input) {
    //Break a string into words
    stringstream strStream(input); 
    string word, largestWord;
    size_t maxLength = 0;

    while (strStream >> word) { 
        if (word.length() > maxLength) {
            maxLength = word.length();
            largestWord = word;
        }
    }

    return largestWord;
}

int main() {
    string input;
    cout << "Enter any sequence of words or line: ";
    getline(cin, input);

    string largestWord = SearchLargestWord(input);
    //Print the output
    if (!largestWord.empty()) {
        cout << "Largest word: " << largestWord <<endl;
    } else {
        cout << "No words found " <<endl;
    }

    return 0;
}

Output

Enter any sequence of words or line: CodDesire is about programming and technology
Largest word: programming
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments