- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ program for length of the longest word in a sentence
Given with the sentence of multiple strings and the task is to find the length of the longest string in the sentence.
Example
Input-: hello I am here Output-: maximum length of a word is: 5 Input-: tutorials point is the best learning platform Output-: maximum length of a word is: 9
Approach used in the below program is as follows −
- Input the string in an array of strings
- Traverse the loop till the end of a sentence is not found
- Traverse one particular string of a sentence and calculate its length. Store the length in a variable
- Pass the integer values of length of strings stored in a temporary variable to a max() function that will return the maximum value from the given lengths of a string.
- Display the maximum length returned by a max() function
Algorithm
Start Step 1-> declare function to calculate longest word in a sentence int word_length(string str) set int len = str.length() set int temp = 0 set int newlen = 0 Loop For int i = 0 and i < len and i++ IF (str[i] != ' ') Increment newlen++ End Else Set temp = max(temp, newlen) Set newlen = 0 End return max(temp, newlen) step 2-> In main() declare string str = "tutorials point is the best learning platfrom" call word_length(str) Stop
Example
#include <iostream> using namespace std; //function to find longest word int word_length(string str) { int len = str.length(); int temp = 0; int newlen = 0; for (int i = 0; i < len; i++) { if (str[i] != ' ') newlen++; else { temp = max(temp, newlen); newlen = 0; } } return max(temp, newlen); } int main() { string str = "tutorials point is the best learning platfrom"; cout <<"maximum length of a word is : "<<word_length(str); return 0; }
Output
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
maximum length of a word is : 9
Advertisements