previous | start | next

C++ string Example 2

Problem: Find and print on separate lines all parts of the string separated by semicolons.

#include <iostream>
#include <string>
#include <cstdlib>

int main()
{
  string s = "Brian W. Kernighan;   The Practice of Programming; Addison Wesley";
  string f;
  size_t start, after;

  start = s.find_first_not_of(" \t;");
  while ( start != string::npos ) {
    after = s.find(";", start);  // set to string::npos if not found
    f = s.substr(start, after - start);
    cout << f << endl;
    start = s.find_first_not_of(" \t;", after);
  }

  return 0;
}

Output:
Brian W. Kernighan
The Practice of Programming
Addison Wesley


previous | start | next