home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C17 / Rparse.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.3 KB  |  43 lines

  1. //: C17:Rparse.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Reverse the order of words in a string
  7. #include <string>
  8. #include <iostream>
  9. #include <vector>
  10. using namespace std;
  11.  
  12. int main() {
  13.   // The ';' characters will be delimiters
  14.   string s("now.;sense;make;to;going;is;This");
  15.   cout << s << endl;
  16.   // To store the words:
  17.   vector<string> strings;
  18.   // The last element of the string:
  19.   int last = s.size();
  20.   // The beginning of the current word:
  21.   int current = s.rfind(';');
  22.   // Walk backward through the string:
  23.   while(current != string::npos){
  24.     // Push each word into the vector.
  25.     // Current is incremented before copying to 
  26.     // avoid copying the delimiter.
  27.     strings.push_back(
  28.       s.substr(++current,last - current));
  29.     // Back over the delimiter we just found, 
  30.     // and set last to the end of the next word
  31.     current -= 2;
  32.     last = current;
  33.     // Find the next delimiter
  34.     current = s.rfind(';', current);
  35.   }
  36.   // Pick up the first word - it's not 
  37.   // preceded by a delimiter
  38.   strings.push_back(s.substr(0, last - current));
  39.   // Print them in the new order:
  40.   for(int j = 0; j < strings.size(); j++)
  41.     cout << strings[j] << " ";
  42. } ///:~
  43.