Advertisement
Guest User

String - Longest Word

a guest
Dec 9th, 2016
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. string s;
  9. cout<<"Enter a Sentence :";
  10. getline(cin, s);
  11.  
  12. int counter = 0;
  13. int max_word = -1;
  14. int len = s.length();
  15. string max = " ";
  16.  
  17.  
  18. for (int i = 0; i < len; i++)
  19. {
  20. if(s[i] != ' ') {
  21. counter++;
  22. //menghitung karakter tanpa spasi
  23. }
  24. //cout<<"i : "<<i<<" | len :"<<len<<endl;
  25. if(s[i] == ' ' || i == len - 1) {
  26. if(counter > max_word) {
  27. max_word = counter;
  28. //cout<<"maxword : "<<max_word<< "i :"<< i<<" len:"<<len<<endl;
  29. //here,handle the end of the string
  30. if(i == len - 1)
  31. max = s.substr(i + 1 - max_word, max_word);
  32. else
  33. max = s.substr(i - max_word, max_word);
  34. }
  35.  
  36. counter = 0;
  37. }
  38. }
  39. cout <<"The longest word in the sentence is "<< max << " with " << max_word <<" letters"<< endl;
  40. return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement