Advertisement
fueanta

Reversed Sentence( by words ) 01

Sep 6th, 2016
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. // Cpp program to get the reversed version of a sentence [reversed by words]
  2. // created on June/July, 2016
  3. // Author: fueanta
  4.  
  5. #include <iostream>
  6. #include <conio.h>
  7. using namespace std;
  8.  
  9. int total_words(string);
  10. string get_words(string &st);
  11.  
  12. int main(void) {
  13.     string str1,str2,str3;
  14.     cout << "Given String: ";
  15.     getline(cin,str1);
  16.     int words= total_words(str1);
  17.     cout << "Total Words: " << words << endl;
  18.     string st[words]; str2=str1;
  19.     for (int i=(words-1);i>=0;i--) {
  20.         st[i]= get_words(str2);
  21.     }
  22.     for (int i=0;i<words;i++) {
  23.         str3+=(st[i]+" ");
  24.     }
  25.     cout << "Reversed String: " << str3 << endl;
  26.     getch();
  27.     return 0;
  28. }
  29.  
  30. int total_words(string st) {
  31.     int counta=0;
  32.     for(int i=0; st[i] ;i++) {
  33.         if(st[i]==' ')
  34.             counta++;
  35.     }
  36.     if ((st[0]!='\0') || (st[0]!=' '))
  37.         counta++;
  38.     return counta;
  39. }
  40.  
  41. string get_words(string &st) {
  42.     string str; int i=0;
  43.     while (st[i]) {
  44.         if (st[i]!= ' ') {
  45.             str+=st[i];
  46.             st.erase(i,1);
  47.         }
  48.         if (st[i]== ' ') {
  49.             st.erase(i,1);
  50.             break;
  51.         }
  52.     }
  53.     return str;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement