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

size_type rfind(const charT* s, size_type pos = npos) const;

size_type rfind(const charT* s, size_type pos, size_type n) const;

size_type rfind(charT c, size_type pos = npos) const noexcept;

These methods work like the analogous find() methods, except that they find the last occurrence of a string or character that starts at or before position pos. If the substring is not found, the method returns npos.

Here’s code for finding the location of the substring "hat" in a longer string, starting at the end of the longer string:

string longer("That is a funny hat.");

string shorter("hat");

size_type loc1 = longer.rfind(shorter);           // sets loc1 to 16

size_type loc2 = longer.rfind(shorter, loc1 - 1); // sets loc2 to 1

The find_first_of() Family

The find_first_of() methods have these prototypes:

size_type find_first_of(const basic_string& str,

                        size_type pos = 0) const noexcept;

size_type find_first_of(const charT* s, size_type pos, size_type n) const;

size_type find_first_of(const charT* s, size_type pos = 0) const;

size_type find_first_of(charT c, size_type pos = 0) const noexcept;

These methods work like the corresponding find() methods, except that instead of looking for a match of the entire substring, they look for the first match for any single character in the substring:

string longer("That is a funny hat.");

string shorter("fluke");

size_type loc1 = longer.find_first_of(shorter);  // sets loc1 to 10

size_type loc2 = longer.find_first_of("fat");    // sets loc2 to 2

The first occurrence of any of the five characters of fluke in longer is the f in funny. The first occurrence of any of three characters of fat in longer is the a in That.

The find_last_of() Family

The find_last_of() methods have these prototypes:

size_type find_last_of (const basic_string& str,

                        size_type pos = npos) const noexcept;

size_type find_last_of (const charT* s, size_type pos, size_type n) const;

size_type find_last_of (const charT* s, size_type pos = npos) const;

size_type find_last_of (charT c, size_type pos = npos) const noexcept;

These methods work like the corresponding rfind() methods, except that instead of looking for a match of the entire substring, they look for the last match for any single character in the substring.

Here’s code for finding the location of the last and next to last occurrences of any of the letters in "fluke" in a longer string:

string longer("That is a funny hat.");

string shorter("hat");

size_type loc1 = longer.find_last_of(shorter);  // sets loc1 to 18

size_type loc2 = longer.find_last_of("any");    // sets loc2 to 17

The last occurrence of any of the three letters of hat in longer is the t in hat. The last occurrence of any of the three characters of any in longer is the a in hat.

The find_first_not_of() Family

The find_first_not_of() methods have these prototypes:

size_type find_first_not_of(const basic_string& str,

                           size_type pos = 0) const noexcept;

size_type find_first_not_of(const charT* s, size_type pos,

                            size_type n) const;

size_type find_first_not_of(const charT* s, size_type pos = 0) const;

size_type find_first_not_of(charT c, size_type pos = 0) const noexcept;

These methods work like the corresponding find_first_of() methods, except that they search for the first occurrence of any character not in the substring.

Here’s code for finding the location of the first two occurrences of any of the letters not in "This" in a longer string:

string longer("That is a funny hat.");

string shorter("This");

size_type loc1 = longer.find_first_not_of(shorter);  // sets loc1 to 2

size_type loc2 = longer.find_first_not_of("Thatch"); // sets loc2 to 4

The a in That is the first character in longer that does not appear in This. The first space in the longer string is the first character not present in Thatch.

The find_last_not_of() Family

The find_last_not_of() methods have these prototypes:

size_type find_last_not_of (const basic_string& str,

                            size_type pos = npos) const noexcept;

size_type find_last_not_of (const charT* s, size_type pos,

                            size_type n) const;

size_type find_last_not_of (const charT* s,

                            size_type pos = npos) const;

size_type find_last_not_of (charT c, size_type pos = npos) const noexcept;

These methods work like the corresponding find_last_of() methods, except that they search for the last occurrence of any character not in the substring.

Here’s code for finding the location of the last two occurrences of any of the letters not in "This" in a longer string:

string longer("That is a funny hat.");

string shorter("That.");

size_type loc1 = longer.find_last_not_of(shorter);     // sets loc1 to 15

size_type loc2 = longer.find_last_not_of(shorter, 10); // sets loc2 to 10

The last space in longer is the last character in longer that does not appear in shorter. The f in the longer string is the last character not present in shorter found up through position 10.

Comparison Methods and Functions

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

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

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

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