Find Longest Word in String
C++
Hard
6 views
Problem Description
Find and print the longest word from a sentence.
Real Life: Text analysis, finding important words.
Step-by-Step Logic:
1. Extract each word
2. Compare length with previous longest
3. Update longest word if current is bigger
4. Return longest word
Official Solution
void string_q11_longest_word() {
string text = "Find the longest word in this sentence";
string currentWord = "";
string longestWord = "";
for(int i = 0; i <= text.length(); i++) {
if(i < text.length() && text[i] != ' ') {
currentWord += text[i];
} else {
if(currentWord.length() > longestWord.length()) {
longestWord = currentWord;
}
currentWord = "";
}
}
cout << "Sentence: " << text << endl;
cout << "Longest word: " << longestWord << endl;
cout << "Length: " << longestWord.length() << endl;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!