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

The string class offers methods and functions for comparing two strings. First, here are the method prototypes:

int compare(const basic_string& str) const noexcept;

int compare(size_type pos1, size_type n1,

            const basic_string& str) const;

int compare(size_type pos1, size_type n1,

            const basic_string& str,

            size_type pos2, size_type n2) const;

int compare(const charT* s) const;

int compare(size_type pos1, size_type n1, const charT* s) const;

int compare(size_type pos1, size_type n1,

            const charT* s, size_type n2 ) const;

These methods use a traits::compare() method that is defined for the particular character type used for the string. The first method returns a value less than 0 if the first string precedes the second string according to the ordering supplied by traits::compare(). It returns 0 if the two strings are the same, and it returns a value greater than 0 if the first string follows the second. If two strings are identical to the end of the shorter of the two strings, the shorter string precedes the longer string.

The following examples compare strings s1 with s3 and s1 with s2:

string s1("bellflower");

string s2("bell");

string s3("cat");

int a13 = s1.compare(s3); // a13 is < 0

int a12 = s1.compare(s2); // a12 is > 0

The second method is like the first, except that it just uses n1 characters, starting from position pos1 in the first string for the comparison.

The following example compares the first four characters in s1 with s2:

string s1("bellflower");

string s2("bell");

int a2 = s1.compare(0, 4, s2); // a2 is 0

The third method is like the first, except that it just uses n1 characters, starting from position pos1 in the first string, and n2 characters, starting from position pos2 in the second string, for the comparison. For example, the following compares the out in stout to the out in about:

string st1("stout boar");

string st2("mad about ewe");

int a3 = st1.compare(2, 3, st2, 6, 3);  // a3 is 0

The fourth method is like the first, except that it uses a character array instead of a string object for the second string.

The fifth and sixth methods essentially are like the third, except that they use a character array instead of a string object for the second string.

The non-member comparison functions are overloaded relational operators:

operator==()

operator<()

operator<=()

operator>()

operator>=()

operator!=()

Each operator is overloaded so that it can compare a string object to a string object, a string object to a C-style string, and a C-style string to a string object. These operators are defined in terms of the compare() method, so they provide a notationally more convenient way of making comparisons.

String Modifiers

The string class provides several methods for modifying strings. Most come with an abundance of overloaded versions so that they can be used with string objects, string arrays, individual characters, and iterator ranges.

Methods for Appending and Adding

You can append one string to another by using the overloaded += operator or by using an append() method. All throw a length_error exception if the result would be longer than the maximum string size. The += operators let you append a string object, a string array, or an individual character to another string:

basic_string& operator+=(const basic_string& str);

basic_string& operator+=(const charT* s);

basic_string& operator+=(charT c);

The append() methods also let you append a string object, a string array, or an individual character to another string. In addition, they let you append part of a string object by specifying an initial position and a number of characters to append or else by specifying a range. You can append part of a string by specifying how many characters of the string to use. The version for appending a character lets you specify how many instances of that character to copy. Here are the prototypes for the various append() methods:

basic_string& append(const basic_string& str);

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

                     size_type n);

template

  basic_string& append(InputIterator first, InputIterator last);

basic_string& append(const charT* s);

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

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

void push_back(charT c);                     // appends 1 copy of c

Here are a couple examples:

string test("The");

test.append("ory");  // test is "Theory"

test.append(3,'!');  // test is "Theory!!!"

The operator+() function is overloaded to enable string concatenation. The overloaded functions don’t modify a string; instead, they create a new string that consists of one string appended to a second. The addition functions are not member functions, and they allow you to add a string object to a string object, a string array to a string object, a string object to a string array, a character to a string object, and a string object to a character. Here are some examples:

string st1("red");

string st2("rain");

string st3 = st1 + "uce";  // st3 is "reduce"

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

Все книги серии 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.

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

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

Все жанры