read a text file and display the largest word and maximum number of characters present in a line from text file
Answers
Answer:
Program for length of the longest word in a sentence
Given a string, we have to find the longest word in the input string and then calculate the number of characters in this word.
Examples:
Input : A computer science portal for geeks
Output : Longest word's length = 8
Input : I am an intern at geeksforgeeks
Output : Longest word's length = 13
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
The idea is simple, we traverse the given string. If we find end of word, we compare length of ended word with result. Else, we increment length of current word.
// C++ program to find the number of
// charters in the longest word in
// the sentence.
#include <iostream>
using namespace std;
int LongestWordLength(string str)
{
int n = str.length();
int res = 0, curr_len = 0, i;
for (int i = 0; i < n; i++) {
// If current character is
// not end of current word.
if (str[i] != ' ')
curr_len++;
// If end of word is found
else {
res = max(res, curr_len);
curr_len = 0;
}
}
// We do max one more time to
// consider last word as there
// won't be any space after
// last word.
return max(res, curr_len);
}
// Driver function
int main()
{
string s =
"I am an intern at geeksforgeeks";
cout << LongestWordLength(s);
return 0;