CSE 40872 Lecture 008

Topic:Strings (STL)
Author: Peter Bui <pbui@cse.nd.edu>
Date: September 16, 2009

Strings (STL)

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;

Common Methods

A lot of the same methods as vector.

size()
Returns length of string.
push_back()
Appends character to end of string.

Append Methods

operator +=

s1 += "Another string";

append()

s1.append("yet another string");

String Methods

c_str()
Returns C string equivalent.
char buffer[MAX_STRLEN];
strncpy(buffer, ss.c_str(), MAX_STRLEN);
substr:
Returns substring.
string s = "Herro Prz";
cout << s.substr(0, 5)  // "Herro"
     << s.substr(6)     // "Prz"
     << endl;

Built-in Algorithms

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");

More STL Algorithms

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());

More STL Algorithms

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()));

More STL Algorithms

void up_print(char c) {
    cout << toupper(c);
}

string s = "herro prz";

for_each(s.begin(), s.end(), up_print);