Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Thinking In C++, 2nd Edition, Volume 2 Standard Libraries& Advanced Topics - Eckel B..pdf
Скачиваний:
314
Добавлен:
24.05.2014
Размер:
2.09 Mб
Скачать

Replacing string characters

insert( ) is particularly nice because it absolves you of making sure the insertion of characters in a string won’t overrun the storage space or overwrite the characters immediately following the insertion point. Space grows and existing characters politely move over to accommodate the new elements. Sometimes, however, this might not be what you want to happen. If the data in string needs to retain the ordering of the original characters relative to one another or must be a specific constant size, use the replace( ) function to overwrite a particular sequence of characters with another group of characters. There are quite a number of overloaded versions of replace( ), but the simplest one takes three arguments: an integer telling where to start in the string, an integer telling how many characters to eliminate from the original string, and the replacement string (which can be a different number of characters than the eliminated quantity). Here’s a very simple example:

//: C01:StringReplace.cpp

// Simple find-and-replace in strings #include <string>

#include <iostream> using namespace std;

int main() {

string s("A piece of text"); string tag("$tag$"); s.insert(8, tag + ' ');

cout << s << endl;

int start = s.find(tag);

cout << "start = " << start << endl; cout << "size = " << tag.size() << endl;

s.replace(start, tag.size(), "hello there"); cout << s << endl;

} ///:~

The tag is first inserted into s (notice that the insert happens before the value indicating the insert point, and that an extra space was added after tag), then it is found and replaced.

You should actually check to see if you’ve found anything before you perform a replace( ). The above example replaces with a char*, but there’s an overloaded version that replaces with a string. Here’s a more complete demonstration replace( )

//: C01:Replace.cpp #include <string> #include <iostream> using namespace std;

void replaceChars(string& modifyMe,

Chapter 14: Templates & Container Classes

34

string findMe, string newChars){

//Look in modifyMe for the "find string"

//starting at position 0

int i = modifyMe.find(findMe, 0);

// Did we find the string to replace? if(i != string::npos)

// Replace the find string with newChars modifyMe.replace(i,newChars.size(),newChars);

}

int main() { string bigNews =

"I thought I saw Elvis in a UFO. " "I have been working too hard.";

string replacement("wig"); string findMe("UFO");

// Find "UFO" in bigNews and overwrite it: replaceChars(bigNews, findMe, replacement); cout << bigNews << endl;

} ///:~

Now the last line of output from replace.cpp looks like this:

I thought I saw Elvis in a wig. I have been working too hard.

If replace doesn’t find the search string, it returns npos. npos is a static constant member of the basic_string class.

Unlike insert( ), replace( ) won’t grow the string’s storage space if you copy new characters into the middle of an existing series of array elements. However, it will grow the storage space if you make a “replacement” that writes beyond the end of an existing array. Here’s an example:

//: C01:ReplaceAndGrow.cpp #include <string>

#include <iostream> using namespace std;

int main() {

string bigNews("I saw Elvis in a UFO. " "I have been working too hard.");

string replacement("wig");

//The first arg says "replace chars

//beyond the end of the existing string": bigNews.replace(bigNews.size(),

Chapter 14: Templates & Container Classes

35

replacement.size(), replacement); cout << bigNews << endl;

} ///:~

The call to replace( ) begins “replacing” beyond the end of the existing array. The output looks like this:

I saw Elvis in a UFO. I have been working too hard.wig

Notice that replace( ) expands the array to accommodate the growth of the string due to “replacement” beyond the bounds of the existing array.

Simple character replacement using the STL replace( ) algorithm

You may have been hunting through this chapter trying to do something relatively simple like replace all the instances of one character with a different character. Upon finding the above section on replacing, you thought you found the answer but then you started seeing groups of characters and counts and other things that looked a bit too complex. Doesn’t string have a way to just replace one character with another everywhere?

The string class by itself doesn’t solve all possible problems. The remainder are relegated to the STL algorithms, because the string class can look just like an STL container (the STL algorithms work with anything that looks like an STL container). All the STL algorithms work on a “range” of elements within a container. Usually that range is just “from the beginning of the container to the end.” A string object looks like a container of characters: to get the beginning of the range you use string::begin( ) and to get the end of the range you use string::end( ). The following example shows the use of the STL replace( ) algorithm to replace all the instances of ‘X’ with ‘Y’:

//: C01:StringCharReplace.cpp #include <string>

#include <algorithm> #include <iostream> using namespace std;

int main() {

string s("aaaXaaaXXaaXXXaXXXXaaa"); cout << s << endl;

replace(s.begin(), s.end(), 'X', 'Y'); cout << s << endl;

} ///:~

Notice that this replace( ) is not called as a member function of string. Also, unlike the string::replace( ) functions which only perform one replacement, the STL replace is replacing all instances of one character with another.

Chapter 14: Templates & Container Classes

36

Соседние файлы в предмете Программирование