This demos these string functions find(), insert(), append() and replace() plus swap() for swapping this string with another, and substr() for getting part of a string.
substr() works with 0, 1 or 2 parameters as both parameters have defaults. The equivalent of the Basic string functions Left(), Mid() and Right() are
- Left(string,len) - substr(0,len)
- Mid(string,startpos,len) - substr(startpos,len)
- Right(string,len) - substr( size()-startpos+1, len)
About Example 3
The first loop indexes a string with the at() function. Then s1 is created as a 10000 long string of spaces. Both reserve() and resize() affect the capacity() before erasing the string and checking if it's empty by calling empty()Then it uses strings s3, starget and s9 to demonstrate string substitution with insert(), replace() and append(). Finally swap() is used to swap two strings.
The max_size() function returns the maximum size of a string.
Note Don't do a find() and compare the result with -1. Always compare string::npos instead. Thsi code below is bad.
int result = s.find("text") ;That is better.
if (result == -1)
...
if (result == string::npos)
...
Using Find
The four overloads of Find() do a case sensitive search a string for a match with a second string or char *. Download Example 6const string s("Humpty Dumpty sat on a wall.") ;
string s2="on a ";
int DPos = s.find("Dumpty") ; // 7
int FPos = s.find('D') ; // 7
int EPos= s.find("sat",16) ; // npos
On the next page : More find functions and comparing strings

