Advertisement
congdantoancau

copy_string_lastword

Nov 26th, 2017
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. char *copyLastWord(char *sz);
  5.  
  6. int main()
  7. {
  8.     char sz[32];
  9.  
  10.     cout << "Your full name: ";
  11.     fflush(stdin); cin.getline(sz, 32);
  12.     cout << endl;
  13.  
  14.     cout << "This is the full name: " << sz << endl;
  15.  
  16.     char *word;
  17.     word = copyLastWord(sz);
  18.     cout << "This is the last word of your name: " << word << endl;
  19.  
  20.     system("pause");
  21.     return 0;
  22. }
  23.  
  24. // Copy the last word of the string
  25. char *copyLastWord(char *sz)
  26. {
  27.     char *word = new char;
  28.     int i, j;
  29.     for (i = 0, j = 0; sz[i] != '\0'; i++)
  30.     {
  31.         if (sz[i] != ' ')
  32.         {
  33.             word[j] = sz[i];
  34.             word[j + 1] = '\0';
  35.             j++;
  36.         }
  37.         else // if (sz[i] == ' ')
  38.             j = 0;
  39.     }
  40.     return word;
  41. }
  42.  
  43.  
  44. char *cutLastWord(char *sz)
  45. {
  46.     char *word = new char;
  47.     strcpy(word, sz);
  48.     strrev(word);
  49.     int i = 0;
  50.     while (word[i] != ' ')
  51.         i++;
  52.     strncpy(word, word, i);
  53.     word[i] = '\0';
  54.     strrev(word);
  55.     return word;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement