Читаем 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.

<p>Concatenation using nonmember overloaded operators</p>

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.

<p>Searching in strings</p>

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 :

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

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

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

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