write a program to accept a string (sentence) and display the longest word and the length of the longest word present in the string. Sample input This is an era of Artificial intelligence. Sample output : Longest word : intelligence. Number of character : 12
Answers
Answer:
// 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;
}
// This code is contributed by
// Smitha Dinesh Semwal.
Answer:
// 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;
}