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

The exact fashion in which the string member functions allocate space for your data depends on the implementation of the library. When we tested one implementation with the previous example, it appeared that reallocations occurred on even word (that is, full-integer) boundaries, with one byte held back. The architects of the string class have endeavored to make it possible to mix the use of C char arrays and C++ string objects, so it is likely that figures reported by StrSize.cpp for capacity reflect that, in this particular implementation, a byte is set aside to easily accommodate the insertion of a null terminator.

<p>Replacing string characters</p>

The insert( ) function 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 you want the size of the string to remain unchanged, use the replace( ) function to overwrite characters. There are quite a number of overloaded versions of replace( ), but the simplest one takes three arguments: an integer indicating where to start in the string, an integer indicating 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 simple example:.

//: C03:StringReplace.cpp

// Simple find-and-replace in strings

#include

#include

using namespace std;

int main() {

  string s("A piece of text");

  string tag("$tag$");

  s.insert(8, tag + ' ');

  assert(s == "A piece $tag$ of text");

  int start = s.find(tag);

  assert(start == 8);

  assert(tag.size() == 5);

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

  assert(s == "A piece hello there of text");

} ///:~

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), and then it is found and replaced.

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

//: C03:Replace.cpp

#include

#include   // for size_t

#include

using namespace std;

void replaceChars(string& modifyMe,

  const string& findMe, const string& newChars) {

  // Look in modifyMe for the "find string"

  // starting at position 0

  size_t 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, findMe.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);

  assert(bigNews == "I thought I saw Elvis in a "

         "wig. I have been working too hard.");

} ///:~

If replace doesn’t find the search string, it returns string::npos. The npos data member is a static constant member of the string class that represents a nonexistent character position.[30] 

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 needed, for example, when you make a "replacement" that would expand the original string beyond the end of the current allocation. Here’s an example:.

//: C03:ReplaceAndGrow.cpp

#include

#include

using namespace std;

int main() {

  string bigNews("I have been working the grave.");

  string replacement("yard shift.");

  // The first arg says "replace chars

  // beyond the end of the existing string":

  bigNews.replace(bigNews.size() - 1,

    replacement.size(), replacement);

  assert(bigNews == "I have been working the "

         "graveyard shift.");

} ///:~

The call to replace( ) begins "replacing" beyond the end of the existing array, which is equivalent to an append operation. Notice that in this example replace( ) expands the array accordingly.

You may have been hunting through this chapter trying to do something relatively simple such as replace all the instances of one character with a different character. Upon finding the previous material 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?.

You can easily write such a function using the find( ) and replace( ) member functions as follows:

//: C03:ReplaceAll.cpp {O}

#include

#include

using namespace std;

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

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

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

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

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

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

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

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

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

Все жанры