Here we take input n as no.of characters in the string and then we use currLen and maxLen two variables to store current length and the maximum length of the word in the string .Firstly both the variables are intialized to zero. Currlen starts from the index-0 and moves upto the space in the string and this currentLen value is given to maxLen , after this the currentLen value is incrmented to the index of the next word.The value of the currentLen and previous currentLen is compared in the for loop upto the null or '/o ' and the highest value is given to maxst variable and the word is given to maxst variable.
#include<iostream>
using namespace std;
int main()
{
// largest word in a sentence
int n;
cout<<"Enter the number of characters in the string"<<endl;
cout<<"Note:Also count the spaces or indentation as 1 character";
cin >>n;
cout<<"Enter the string : ";
cin.ignore();//function to ignore the spaces in the input string
char arr[n+1];
cin.getline (arr, n+1);//a standard library function that is used to read a string or a line from an input stream
cout<<"press enter";
cin.ignore();
int i=0;
int currLen= 0, maxLen = 0;
int st=0, maxst=0;
while (1)
{
if(arr[i] == ' '|| arr[i] == '\0')
{
if(currLen >maxLen)
{
maxLen =currLen;
maxst=st;
}
currLen = 0;
st=i+1;
}
else
currLen++;
if(arr [i] == '\0')
break;
i++;
}
cout <<"the length of the maximum word is "<< maxLen << endl;
for(int i=0; i<maxLen; i++){
cout << arr[i+maxst];
}
return 0;
}
Enter the number of characters in the string
Note:Also count the spaces or indentation as 1 character
50
Enter the string : an apple a day keeps the doctor away
press enter
Comments