Advertisement
janac

Separate a sentence into words

Nov 18th, 2021
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. // Separate a sentence into words.
  6. int main()
  7. {
  8.     string sentence; // User input.
  9.  
  10.     cout << "Enter a sentence." << endl;
  11.     getline(cin, sentence); // Get the user's sentence.
  12.  
  13.     int space_location = 0; // Location of a space.
  14.     int start_position = 0; // Begin a new word.
  15.     int length = 0; // Length of the word.
  16.     string word; // A word.
  17.  
  18.     cout << "Here is your sentence, one word at a time:" << endl;
  19.     if (!sentence.empty()) // If the user entered a sentence,
  20.     {
  21.         // While there is a space in the sentence,
  22.         while ( (space_location = sentence.find(" ", start_position)) != string::npos)
  23.         {
  24.             // Get the length of the word.
  25.             length = space_location - start_position;
  26.  
  27.             // Get the word.
  28.             word = sentence.substr(start_position, length);
  29.  
  30.             // Display the word.
  31.             cout << word << endl;
  32.  
  33.             // This is the start of the next word.
  34.             start_position = space_location + 1;
  35.         }
  36.  
  37.         // If there are no more spaces,
  38.         // Get the length of the last word.
  39.         length = sentence.size() - start_position;
  40.  
  41.         // Get the last word.
  42.         word = sentence.substr(start_position, length);
  43.  
  44.         // Display the last word.
  45.         cout << word << endl;
  46.     }
  47.     else // If the user did not enter anything,
  48.     {
  49.         cout << "No sentence was entered." << endl;
  50.     }
  51.  
  52.     // End the program.
  53.     return 0;
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement