Читаем Thinking In C++. Volume 2: Practical Programming полностью

string& replaceAll(string& context, const string& from,

  const string& to) {

  size_t lookHere = 0;

  size_t foundHere;

while ((foundHere = context.find(from, lookHere))

  != string::npos) {

    context.replace(foundHere, from.size(), to);

lookHere = foundHere + to.size();

  }

  return context;

} ///:~


The version of find( ) used here takes as a second argument the position to start looking in and returns string::npos if it doesn’t find it. It is important to advance the position held in the variable lookHere past the replacement string, of course, in case from is a substring of to. The following program tests the replaceAll function:.

//: C03:ReplaceAllTest.cpp

//{-msc}

//{L} ReplaceAll

#include

#include

using namespace std;


string& replaceAll(string& context, const string& from,

  const string& to);


int main() {

  string text = "a man, a plan, a canal, panama";

  replaceAll(text, "an", "XXX");

  assert(text == "a mXXX, a plXXX, a cXXXal, pXXXama");

} ///:~


As you can see, the string class by itself doesn’t solve all possible problems. Many solutions have been left to the algorithms in the Standard library,[31] because the string class can look just like an STL sequence (by virtue of the iterators discussed earlier). All the generic 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 replace( ) algorithm to replace all the instances of the single character ‘X’ with ‘Y’:.

//: C03:StringCharReplace.cpp

#include

#include

#include

using namespace std;


int main() {

  string s("aaaXaaaXXaaXXXaXXXXaaa");

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

  assert(s == "aaaYaaaYYaaYYYaYYYYaaa");

} ///:~


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

The replace( ) algorithm only works with single objects (in this case, char objects) and will not replace quoted char arrays or string objects. Since a string behaves like an STL sequence, a number of other algorithms can be applied to it, which might solve other problems that are not directly addressed by the string member functions.

Concatenation using nonmember overloaded operators

One of the most delightful discoveries awaiting a C programmer learning about C++ string handling is how simply strings can be combined and appended using operator+ and operator+=. These operators make combining strings syntactically similar to adding numeric data.

//: C03:AddStrings.cpp

#include

#include

using namespace std;


int main() {

  string s1("This ");

  string s2("That ");

  string s3("The other ");

  // operator+ concatenates strings

  s1 = s1 + s2;

  assert(s1 == "This That ");

  // Another way to concatenates strings

  s1 += s3;

  assert(s1 == "This That The other ");

  // You can index the string on the right

  s1 += s3 + s3[4] + "ooh lala";

  assert(s1 == "This That The other The other "

        "oooh lala");

} ///:~



Using the operator+ and operator+= operators is a flexible and convenient way to combine string data. On the right side of the statement, you can use almost any type that evaluates to a group of one or more characters.

Searching in strings

The find family of string member functions allows you to locate a character or group of characters within a given string. Here are the members of the find family and their general usage :

Перейти на страницу:

Похожие книги

3ds Max 2008
3ds Max 2008

Одни уверены, что нет лучшего способа обучения 3ds Мах, чем прочитать хорошую книгу. Другие склоняются к тому, что эффективнее учиться у преподавателя, который показывает, что и как нужно делать. Данное издание объединяет оба подхода. Его цель – сделать освоение 3ds Мах 2008 максимально быстрым и результативным. Часто после изучения книги у читателя возникают вопросы, почему не получился тот или иной пример. Видеокурс – это гарантия, что такие вопросы не возникнут: ведь автор не только рассказывает, но и показывает, как нужно работать в 3ds Мах.В отличие от большинства интерактивных курсов, где работа в 3ds Мах иллюстрируется на кубиках-шариках, данный видеокурс полностью практический. Все приемы работы с инструментами 3ds Мах 2008 показаны на конкретных примерах, благодаря чему после просмотра курса читатель сможет самостоятельно выполнять даже сложные проекты.

Владимир Антонович Верстак , Владимир Верстак

Программирование, программы, базы данных / Программное обеспечение / Книги по IT