



(39 votes)/* string.cpp by detour@metalshell.com * * Example on using the string class from the STL. * * http://www.metalshell.com/ * */ #include <iostream> #include <string> #include <stdio.h> using namespace std; int main() { string str; string str2; /* You can assign values using normal = operator */ str = "Jimi Thing\n"; str2 = "Jimi Thing\n"; /* Can be compared against other strings */ if(str == str2) cout << str; cout << "The length of str is: " << str.length() << endl; /* You pull text out of the string using substr */ str2 = str.substr(0,4) + "\n"; cout << "str2 = " << str2; /* Notice Jimi gets replace with Little even though Little is longer then Jimi */ str.replace(0,4,"Little"); cout << "str = " << str; /* C Strings are null terminated areas of characters */ printf("str = %s", str.c_str()); /* First occurance of Little is stored in p1 */ string::size_type p1 = str.find("Little"); /* Replace the first Little found with Jimi */ str.replace(p1, 6, "Jimi"); cout << "str = " << str; /* Another way to turn it back */ str.replace(str.find("Jimi"),4,"Little"); cout << "str = " << str; /* If erase is given no arguments the whole string is cleared */ str.erase(); cout << "str = " << str; return 0; }