Topic: | Strings (STL) |
---|---|
Author: | Peter Bui <pbui@cse.nd.edu> |
Date: | September 16, 2009 |
STL provides string class that behaves like a vector of chars.
string s1;
string s2("Herro Prz");
string s3(s2);
string s4(10, 'x');
s1 = "blah blah";
s1 = s2;
A lot of the same methods as vector.
operator +=
s1 += "Another string";
append()
s1.append("yet another string");
char buffer[MAX_STRLEN];
strncpy(buffer, ss.c_str(), MAX_STRLEN);
string s = "Herro Prz";
cout << s.substr(0, 5) // "Herro"
<< s.substr(6) // "Prz"
<< endl;
STL includes a few algorithms such as find, find_first_of, find_last_of, find_first_not_of, find_last_not_of.
string s1 = "Who likes short shorts?.";
string s2 = "short";
if (s1.find(s2) != string::npos)
s1.replace(s1.find_last_of(s2), s2.size(), "pant");
Check out #include <algorithm>:
string s1 = "abcdef";
string s2 = "123456";
string s3(s1.size() + s2.size());
random_shuffle(s1.begin(), s1.end());
random_shuffle(s2.begin(), s2.end());
sort(s1.begin(), s1.end());
sort(s2.begin(), s2.end());
merge(s1.begin(), s1.end(), s2.begin(), s2.end(), s3.begin());
string s = "herro prz";
sort(s.begin(), s.end());
// Print out all permutations of s
do {
cout << s << endl;
} while (next_permutation(s.begin(), s.end()));
void up_print(char c) {
cout << toupper(c);
}
string s = "herro prz";
for_each(s.begin(), s.end(), up_print);