Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- using namespace std;
- int main()
- {
- string s;
- cout<<"Enter a Sentence :";
- getline(cin, s);
- int counter = 0;
- int max_word = -1;
- int len = s.length();
- string max = " ";
- for (int i = 0; i < len; i++)
- {
- if(s[i] != ' ') {
- counter++;
- //menghitung karakter tanpa spasi
- }
- //cout<<"i : "<<i<<" | len :"<<len<<endl;
- if(s[i] == ' ' || i == len - 1) {
- if(counter > max_word) {
- max_word = counter;
- //cout<<"maxword : "<<max_word<< "i :"<< i<<" len:"<<len<<endl;
- //here,handle the end of the string
- if(i == len - 1)
- max = s.substr(i + 1 - max_word, max_word);
- else
- max = s.substr(i - max_word, max_word);
- }
- counter = 0;
- }
- }
- cout <<"The longest word in the sentence is "<< max << " with " << max_word <<" letters"<< endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement