Читаем C++ Primer Plus полностью

string st4 = 't' + st2;    // st4 is "train"

string st5 = st1 + st2;    // st5 is "redrain"

More Assignment Methods

In addition to the basic assignment operator, the string class provides assign() methods, which allow you to assign a whole string or a part of a string or a sequence of identical characters to a string object. Here are the prototypes for the various assign() methods:

basic_string& assign(const basic_string& str);

basic string& assign(basic_string&& str) noexcept;   // C++11

basic_string& assign(const basic_string& str, size_type pos,

                     size_type n);

basic_string& assign(const charT* s, size_type n);

basic_string& assign(const charT* s);

basic_string& assign(size_type n, charT c); // assign n copies of c

template

  basic_string& assign(InputIterator first, InputIterator last);

basic_string& assign(initializer_list);  // C++11

Here are a couple examples:

string test;

string stuff("set tubs clones ducks");

test.assign(stuff, 1, 5);   // test is "et tu"

test.assign(6, '#");        // test is "######"

The assign() method with an rvalue reference (added by C++11) allows for move semantics, and the second new assign() method allows one to assign an initializer_list to a string object.

Insertion Methods

The insert() methods let you insert a string object, a string array, a character, or several characters into a string object. The methods are similar to the append() methods, except that they take an additional argument, indicating where to insert the new material. This argument may be a position or an iterator. The material is inserted before the insertion point. Several of the methods return a reference to the resulting string. If pos1 is beyond the end of the target string or if pos2 is beyond the end of the string to be inserted, a method throws an out_of_range exception. If the resulting string will be larger than the maximum size, a method throws a length_error exception. Here are the prototypes for the various insert() methods:

basic_string& insert(size_type pos1, const basic_string& str);

basic_string& insert(size_type pos1, const basic_string& str,

                     size_type pos2, size_type n);

basic_string& insert(size_type pos, const charT* s, size_type n);

basic_string& insert(size_type pos, const charT* s);

basic_string& insert(size_type pos, size_type n, charT c);

iterator insert(const_iterator p, charT c);

iterator insert(const_iterator p, size_type n, charT c);

template

  void insert(iterator p, InputIterator first, InputIterator last);

iterator insert(const_iterator p, initializer_list); // C++11

For example, the following code inserts the string "former " before the b in "The banker.":

string st3("The banker.");

st3.insert(4, "former ");

Then the following code inserts the string " waltzed" (not including the !, which would be the ninth character) just before the period at the end of "The former banker.":

st3.insert(st3.size() - 1, " waltzed!", 8);

Erase Methods

The erase() methods remove characters from a string. Here are their prototypes:

basic_string& erase(size_type pos = 0, size_type n = npos);

iterator erase(const_iterator position);

iterator erase(const_iterator first, iterator last);

void pop_back();

The first form removes the character from position pos to n characters later or the end of the string, whichever comes first. The second removes the single character referenced by the iterator position and returns an iterator to the next element or if there are no more elements, returns end(). The third removes the characters in the range [first, last); that is, including first and up to but not including last. The method returns an iterator to the element following the last element erased. Finally, the pop_back() method removes the last character in the string.

Replacement Methods

The various replace() methods identify part of a string to be replaced and identify the replacement. The part to be replaced can be identified by an initial position and a character count or by an iterator range. The replacement can be a string object, a string array, or a particular character duplicated several times. Replacement string objects and arrays can further be modified by indicating a particular portion, using a position and a count, just a count, or an iterator range. Here are the prototypes for the various replace() methods:

basic_string& replace(size_type pos1, size_type n1, const basic_string& str);

basic_string& replace(size_type pos1, size_type n1, const basic_string& str,

                      size_type pos2, size_type n2);

basic_string& replace(size_type pos, size_type n1, const charT* s,

                      size_type n2);

basic_string& replace(size_type pos, size_type n1, const charT* s);

basic_string& replace(size_type pos, size_type n1, size_type n2, charT c);

basic_string& replace(const_iterator i1, const_iterator i2,

                      const basic_string& str);

basic_string& replace(const_iterator i1, const_iterator i2,

                      const charT* s, size_type n);

basic_string& replace(const_iterator i1, const_iterator i2,

                      const charT* s);

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

Все книги серии Developer's Library

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

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

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

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

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

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

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

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

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

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