// Phil Ottewell's STL Course - http://www.pottsoft.com/home/stl/stl.htmlx // // Example 5.1 © Phil Ottewell 1997 // // Purpose: // Demonstrate use of standard string class // ANSI C Headers #include // C++ STL Headers #include #include #include #ifdef _WIN32 using namespace std; #endif int main( int argc, char *argv[] ) { size_t ip; string needle = "needle"; // Initialize with C style string literal string line("my string"); // Ditto string haystack(line,3,6); // Initialize with another string, line, // starting at element 3, i.e. "string" string string3(line,0,2); // Initialize with first 2 characters of // line, i.e. "my" string s1; // INITIALIZING with single character, e.g. string s2; // = 'A' or ('A') or an integer NOT ALLOWED // These will currently have .length() of zero string dashes(80,'-'); // You can initialize using a character like // this, and character ASSIGNMENT is legal char old_c_string[64]; // Concatenation using + operator s1 = "Now is the Winter "; s2 = "of our discontent made Summer"; cout << "s1 = \"" << s1 << "\"," << "s2 = \"" << s2 << "\"\n" << "s1 + s2 = \"" << s1 + s2 << "\"" << endl << dashes << endl; // Find a substring in a string haystack = "Where is that " + needle + ", eh ?"; cout << "haystack = \"" << haystack << "\"" << endl; ip = haystack.find(needle); // Use substr function to get substring - use string::npos (the "too large" // character count) to get the rest of the string cout << "ip = haystack.find(needle) found \"" << haystack.substr(ip,string::npos ) << "\" at position ip = " << ip << endl << dashes << endl; // Demonstrate use of Algorithms with strings line = "Naomi, sex at noon taxes, I moan"; cout << line << " [Algorithm: reverse(line.begin(),line.end())]" << endl; reverse( line.begin(), line.end() ); cout << line << " [line.length() = " << line.length() << "]" << endl << dashes << endl; // Passing a string to a function requiring a C style string line = "copyright"; strncpy( old_c_string, line.c_str() , sizeof(old_c_string)-1 ); old_c_string[sizeof(old_c_string)-1] = '\0'; cout << "strncpy \"" << line << "\" to c string which now contains \"" << old_c_string << "\"" << endl << dashes << endl; // Insert into a string s1 = "piggy middle"; s2 = "in the "; cout << "s1 = \"" << s1 << "\", s2 = \"" << s2 << "\"" << endl; s1.insert(6,s2); // Insert s2 in s1 cout << "s1.insert(6,s2) = " << s1 << endl << dashes << endl; // Erase cout << "[Use s1.erase(ip,4) to get rid of \"the \"]" << endl; ip = s1.find("the"); if ( ip != string::npos ) s1.erase( ip, 4 ); // Note check on ::npos cout << s1 << endl << dashes << endl; // Replace cout << "[Use s1.replace(ip,2,\"is not in the\") to replace " << "\"in\" with \"is not in the\"]" << endl; ip = s1.find("in"); // Note inequality check on string::npos to see if search string was found if ( ip != string::npos ) s1.replace( ip, 2, "is not in the" ); cout << s1 << endl << dashes << endl; return( EXIT_SUCCESS ); }