/* COMPUTER SCIENCE 2 * Lab 2 - Introduction to C++ * Example usage of strings and vectors * * Author: Don Miner * Date: February 4, 2007 * * lab2example.cpp * This program takes in a sentence and a word, then removes this word from the sentence. * * To compile: * g++ -ansi -Wall -o lab2example lab2example.cpp * * Sample run: $ ./lab2example Please enter the word you will remove from the sentence: brown Please enter the sentence: the quick brown fox wrote some C++ code. BROWN brown Brown brown. The new sentence is: the quick fox wrote some C++ code. BROWN Brown brown. * */ #include #include #include using namespace std; // remove takes in a vector of strings and returns a vector of strings // that does not have the word "item" in it vector remove(vector list, string item); // join takes in a vector and a separator and returns a single string that is // the strings of the list joined together, with "separator" inbetween each string join(vector list, string separator); int main() { cout << "Please enter the word you will remove from the sentence: "; // Take one word through input and store it in "to_remove" string to_remove; cin >> to_remove; cout << "Please enter the sentence: "; // Scan one word at a time, into input // This well end when End Of File is reached // (while using the command line, EOF is ctrl-D) string input; vector sentence; while(cin >> input) { // "input" now stores one word // Add "input" to the end of "sentence" (push_back) sentence.push_back(input); } // remove the word from the sentence sentence = remove(sentence, to_remove); // join the words in the sentence into one string string output = join(sentence, " "); cout << "The new sentence is: " << output << endl; return 0; } // remove takes in a vector of strings and returns a vector of strings // that does not have the word "item" in it vector remove(vector list, string item) { // create a temporary vector vector out; // iterate through "list" and push each word onto the temporary vector // if it is not equal for(unsigned int i = 0; i < list.size(); i++) { // notice the usage of != if(list.at(i) != item) { out.push_back(list.at(i)); } } return out; } // join takes in a vector and a separator and returns a single string that is // the strings of the list joined together, with "separator" inbetween each string join(vector list, string separator) { // create a temporary string string out = ""; // iterate through "list" and *add* each string to the temporary string for(unsigned int i = 0; i < list.size(); i++) { // *add* to the end of the temporary string out += list.at(i); // inject the separator inbetween each token if(i != list.size() - 1) { out += separator; } } return out; }