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

string find member functionWhat/how it finds
 find( )Searches a string for a specified character or group of characters and returns the starting position of the first occurrence found or npos if no match is found. (npos is a const of –1 [cast as a std::size_t] and indicates that a search failed.)
 find_first_of( )Searches a target string and returns the position of the first match of any character in a specified group. If no match is found, it returns npos.
 find_last_of( )Searches a target string and returns the position of the last match of any character in a specified group. If no match is found, it returns npos.
 find_first_not_of( )Searches a target string and returns the position of the first element that doesn’t match any character in a specified group. If no such element is found, it returns npos.
 find_last_not_of( )Searches a target string and returns the position of the element with the largest subscript that doesn’t match any character in a specified group. If no such element is found, it returns npos.
 rfind( )Searches a string from end to beginning for a specified character or group of characters and returns the starting position of the match if one is found. If no match is found, it returns npos.

The simplest use of find( ) searches for one or more characters in a string. This overloaded version of find( ) takes a parameter that specifies the character(s) for which to search and optionally a parameter that tells it where in the string to begin searching for the occurrence of a substring. (The default position at which to begin searching is 0.) By setting the call to find inside a loop, you can easily move through a string, repeating a search to find all the occurrences of a given character or group of characters within the string.

The following program uses the method of The Sieve of Eratosthenes to find prime numbers less than 50. This method starts with the number 2, marks all subsequent multiples of 2 as not prime, and repeats the process for the next prime candidate. Notice that we define the string object sieveChars using a constructor idiom that sets the initial size of the character array and writes the value ‘P’ to each of its member.

//: C03:Sieve.cpp

//{L} ../TestSuite/Test

#include

#include

#include

#include "../TestSuite/Test.h"

using namespace std;

class SieveTest : public TestSuite::Test {

  string sieveChars;

public:

  // Create a 50 char string and set each

  // element to 'P' for Prime

SieveTest() : sieveChars(50, 'P') {}

  void run() {

    findPrimes();

    testPrimes();

  }

  bool isPrime(int p) {

    if (p == 0 || p == 1) return false;

    int root = int(sqrt(double(p)));

    for (int i = 2; i <= root; ++i)

      if (p % i == 0) return false;

    return true;

  }

  void findPrimes() {

    // By definition neither 0 nor 1 is prime.

    // Change these elements to "N" for Not Prime

    sieveChars.replace(0, 2, "NN");

    // Walk through the array:

    size_t sieveSize = sieveChars.size();

    int root = int(sqrt(double(sieveSize)));

    for (int i = 2; i <= root; ++i)

      // Find all the multiples:

      for (size_t factor = 2; factor * i < sieveSize;

           ++factor)

        sieveChars[factor * i] = 'N';

  }

  void testPrimes() {

    size_t i = sieveChars.find('P');

    while (i != string::npos) {

      test_(isPrime(i++));

      i = sieveChars.find('P', i);

    }

    i = sieveChars.find_first_not_of('P');

    while (i != string::npos) {

      test_(!isPrime(i++));

      i = sieveChars.find_first_not_of('P', i);

    }

  }

};

int main() {

  SieveTest t;

  t.run();

  return t.report();

} ///:~

The find( ) function allows you to walk forward through a string, detecting multiple occurrences of a character or a group of characters, and find_first_not_of( ) allows you to find other characters or substrings.

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

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

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

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

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

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

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

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

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