/* * Program to illustrate some string capabilities: * length * substr * find_first_not_of * find_first_of * * Main and split function to take a long string and break it up into words * Copied from Budd textbook, chapt 7, but converted to use arrays instead * of lists (which we haven't covered yet) * * Author: Michael A. Redmond * * Written: 02/16/99 */ #include #include using namespace std; // return how many words were found // make sure caller sends a big enough array int split (string & text, const string & separators, string words[]) { int numWords = 0; int n = text.length(); // find first non-separator char (pass separators and // position to start looking) int start = text.find_first_not_of(separators,0); // loop as long as there is still a non-separator char while ((start >= 0) && (start < n)) { // find end of current word (pass separators and // position to start looking) int stop = text.find_first_of(separators,start); // avoid running past end of text if ((stop < 0) || (stop > n)) { stop = n; } // add word to array of words // substr is passed a position to start and a length words[numWords] = text.substr(start, stop-start); // cout << "current word: " << words[numWords] << endl; numWords++; // find start of next word start = text.find_first_not_of(separators,stop+1); // cout << " start: " << start << " "; } return numWords; } void main() { // string text = "it was the best of times, it was the worst of times."; string text = "There was a time, not so long ago, when programmers used Pascal, not C++."; // below won't work well because cin into a string just gets up to white space // string text; // cout << "Please enter a string of words " << endl; // cin >> text; string allWords[100]; int num = split(text," .,!?:",allWords); // display words cout << "The words are: " << endl; for (int cnt = 0;cnt < num;cnt++){ cout << " " << allWords[cnt] << endl; } }