Searching a Substring Within a String
Searching a substring within a string is another common task in text-oriented apps. The Standard Library defines several specialized overloaded versions of string::find(). These overloaded versions take const string&, const char *, or char as a sought-after value. For the sake of brevity, I will focus only on locating a string object within another string object:
string phrase="Franco's rain in Spain";
string sought = "rain";
int pos=phrase.find(sought); // pos=9
find() returns the position of sought's first character within phrase. This position can then be used for further manipulations such as deleting the sought-after string or replacing it with another value. Test if the search succeeded like this:
If the sought-after string wasn't found, find() will return string::npos
, which is an agreed-upon constant value indicating an invalid position in any string.
Replacing a Substring
To replace the sought-after value, use the replace() function which also has several overloaded versions. Again, use the canonical version which takes three arguments: the position to which the replacement string should be written, the length of the substring to be replaced, and an overriding string. For example, the following snippet corrects a typo in phrase by replacing 'rain' with 'reign':
phrase.replace(pos, sought.size(), replacement);
shows what the output looks like.
In fact, the search and replace operations can be combined into a single statement:
Remember that this form should be used only when you're certain that the sought-after value exists in the containing string (this may be the case if the processed sentence is machine-generated, for example). If there's no such guarantee, check whether the search operation succeeded before calling replace().
|Figure 2: replace() automatically adjusts its object's capacity to fit to its new size.
I silently ignored an issue that may have perturbed you: 'reign' is one character longer than the replaced value 'rain' and yet the program didn't extend the original string's size before calling replace(). Is this an oversight? No, it isn't. replace() automatically adjusts its object's capacity to fit to its new size. To convince the skeptics among you, I'll use a longer replacement string and check the string object's capacity before and after the replace() call:
cout<<"original string capacity: "<<phrase. capacity ()<<endl;
string replacement "reign in Spain should see out the forties";
string sought = "rain in Spain";
phrase.replace(phrase.find(sought), sought.size(), replacement);
cout<<"new capacity: "<<phrase. capacity ()<<endl;
As you can see, the resulting string and its capacity were expanded automatically:
And that, my friends, is the beauty of std::string!