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

Comparing strings is inherently different from comparing numbers. Numbers have constant, universally meaningful values. To evaluate the relationship between the magnitudes of two strings, you must make a lexical comparison. Lexical comparison means that when you test a character to see if it is "greater than" or "less than" another character, you are actually comparing the numeric representation of those characters as specified in the collating sequence of the character set being used. Most often this will be the ASCII collating sequence, which assigns the printable characters for the English language numbers in the range 32 through 127 decimal. In the ASCII collating sequence, the first "character" in the list is the space, followed by several common punctuation marks, and then uppercase and lowercase letters. With respect to the alphabet, this means that the letters nearer the front have lower ASCII values than those nearer the end. With these details in mind, it becomes easier to remember that when a lexical comparison that reports s1 is "greater than" s2, it simply means that when the two were compared, the first differing character in s1 came later in the alphabet than the character in that same position in s2.

C++ provides several ways to compare strings, and each has advantages. The simplest to use are the nonmember, overloaded operator functions: operator ==, operator != operator >, operator <, operator >=, and operator <=.

//: C03:CompStr.cpp

//{L} ../TestSuite/Test

#include

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

using namespace std;

class CompStrTest : public TestSuite::Test {

public:

  void run() {

    // Strings to compare

    string s1("This");

    string s2("That");

    test_(s1 == s1);

    test_(s1 != s2);

    test_(s1 > s2);

    test_(s1 >= s2);

    test_(s1 >= s1);

    test_(s2 < s1);

    test_(s2 <= s1);

    test_(s1 <= s1);

  }

};

int main() {

  CompStrTest t;

  t.run();

  return t.report();

} ///:~

The overloaded comparison operators are useful for comparing both full strings and individual string character elements.

Notice in the following code fragment the flexibility of argument types on both the left and right side of the comparison operators. For efficiency, the string class provides overloaded operators for the direct comparison of string objects, quoted literals, and pointers to C-style strings without having to create temporary string objects.

// The lvalue is a quoted literal and

// the rvalue is a string

if("That" == s2)

  cout << "A match" << endl;

// The left operand below is a string and the right is a

// pointer to a C-style null terminated string

if(s1 != s2.c_str())

  cout << "No match" << endl;

The c_str( ) function returns a const char* that points to a C-style, null-terminated string equivalent to the contents of the string object. This comes in handy when you want to pass a string to a standard C function, such as atoi( ) or any of the functions defined in the header. It is an error to use the value returned by c_str( ) as non-const argument to any function.

You won’t find the logical not (!) or the logical comparison operators (&& and ||) among operators for a string. (Neither will you find overloaded versions of the bitwise C operators &, |, ^, or ~.) The overloaded nonmember comparison operators for the string class are limited to the subset that has clear, unambiguous application to single characters or groups of characters.

The compare( ) member function offers you a great deal more sophisticated and precise comparison than the nonmember operator set. It provides overloaded versions that allow you to compare two complete strings, part of either string to a complete string, and subsets of two strings. The following example compares complete strings:.

//: C03:Compare.cpp

// Demonstrates compare(), swap()

#include

#include

using namespace std;

int main() {

  string first("This");

  string second("That");

  assert(first.compare(first) == 0);

  assert(second.compare(second) == 0);

  // Which is lexically greater?

  assert(first.compare(second) > 0);

  assert(second.compare(first) < 0);

  first.swap(second);

  assert(first.compare(second) < 0);

  assert(second.compare(first) > 0);

} ///:~

The swap( ) function in this example does what its name implies: it exchanges the contents of its object and argument. To compare a subset of the characters in one or both strings, you add arguments that define where to start the comparison and how many characters to consider. For example, we can use the overloaded version of compare( ):.

s1.compare(s1StartPos, s1NumberChars, s2, s2StartPos, s2NumberChars);.

Here’s an example:.

//: C03:Compare2.cpp

// Illustrate overloaded compare()

#include

#include

using namespace std;

int main() {

  string first("This is a day that will live in infamy");

  string second("I don't believe that this is what "

 "I signed up for");

  // Compare "his is" in both strings:

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

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

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

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

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

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

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

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

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