- Determine the length of a string
int ← length()
- Returns the number of characters in the string
(size()
does same thing)
string s = "hello";
int len = s.length(); // 5
len = s.size(); // 5
- Determine if a string is empty
bool ← empty()
- Returns true
if the string
has a length of 0, false
otherwise
string s = "";
if (s.empty()) // true
cout << "s is empty";
- Erase a portion of a string
erase(int start, int numChars)
- Erases all chars beginning at start
and going to the right. numChars
limit is optional
string s = "erase this";
s.erase(0, 6); // Leaves "this"
s.erase(2); // Leaves "th"
- Get a substring of a larger string
string ← substr(int start, int numChars)
- Returns the string beginning
at start
that is numChars
in length. numChars
is optional
string a = "a nice play";
string b = a.substr(2); // "nice play"
b = a.substr(2, 4); // "nice"
- Finding a string within a string
int ← find(string find, int start)
- Returns the starting location
of the first occurance of find
in the string,
string::npos
if find
string could
not be found. start
is the optional starting
location
string s = "this is a test";
int pos = s.find("is"); // 2
pos = s.find("is", 3); // 5
pos = s.find("xyz");
if (pos == string::npos)
cout << "Could not find xyz";
- Finding one char out of a group of chars in a string
int ← find_first_of(string find, int start)
- Returns the first location
of any chars in the find
in the string, string::npos
if none of the chars could be found. start
is the optional starting
location
string s = "this is a test";
int pos = s.find_first_of("iou"); // 2
pos = s.find_first_of("iou", 3); // 5
pos = s.find_first_of("xyz");
if (pos == string::npos)
cout << "Could not find x, y, or z";
- Replace chars from a string with another string
replace(int start, int numChars, string replacement)
- Replaces
the chars beginning at start
that is numChars
in length with replacement
string s = "this is a test";
s.replace(5, 2, "was"); // "this was a test"