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

The next string, heyMom, is initialized by the literal argument "Where are my socks?" This form of initialization uses a quoted character array as a parameter to the string constructor. By contrast, standardReply is simply initialized with an assignment. The last string of the group, useThisOneAgain, is initialized using an existing C++ string object. Put another way, this example illustrates that string objects let you do the following:.

·         Create an empty string and defer initializing it with character data.

·         Initialize a string by passing a literal, quoted character array as an argument to the constructor.

·         Initialize a string using the equal sign (=).

·         Use one string to initialize another.

//: C03:SmallString.cpp

#include

using namespace std;

int main() {

  string imBlank;

  string heyMom("Where are my socks?");

  string standardReply = "Beamed into deep "

    "space on wide angle dispersion?";

  string useThisOneAgain(standardReply);

} ///:~

These are the simplest forms of string initialization, but variations offer more flexibility and control. You can do the following:

 Use a portion of either a C char array or a C++ string.

 Combine different sources of initialization data using operator+.

 Use the string object’s substr( ) member function to create a substring.

Here’s a program that illustrates these features.

//: C03:SmallString2.cpp

#include

#include

using namespace std;

int main() {

  string s1

    ("What is the sound of one clam napping?");

  string s2

    ("Anything worth doing is worth overdoing.");

  string s3("I saw Elvis in a UFO");

  // Copy the first 8 chars

  string s4(s1, 0, 8);

  cout << s4 << endl;

  // Copy 6 chars from the middle of the source

  string s5(s2, 15, 6);

  cout << s5 << endl;

  // Copy from middle to end

  string s6(s3, 6, 15);

  cout << s6 << endl;

  // Copy all sorts of stuff

  string quoteMe = s4 + "that" +

  // substr() copies 10 chars at element 20

  s1.substr(20, 10) + s5 +

  // substr() copies up to either 100 char

  // or eos starting at element 5

  "with" + s3.substr(5, 100) +

  // OK to copy a single char this way

  s1.substr(37, 1);

  cout << quoteMe << endl;

} ///:~

The string member function substr( ) takes a starting position as its first argument and the number of characters to select as the second argument. Both arguments have default values. If you say substr( ) with an empty argument list, you produce a copy of the entire string; so this is a convenient way to duplicate a string.

Here’s the output from the program:

What is

doing

Elvis in a UFO

What is that one clam doing with Elvis in a UFO?

Notice the final line of the example. C++ allows string initialization techniques to be mixed in a single statement, a flexible and convenient feature. Also notice that the last initializer copies just one character from the source string.

Another slightly more subtle initialization technique involves the use of the string iterators string::begin( ) and string::end( ). This technique treats a string like a container object (which you’ve seen primarily in the form of vector so far—you’ll see many more containers in Chapter 7), which uses iterators to indicate the start and end of a sequence of characters. In this way you can hand a string constructor two iterators, and it copies from one to the other into the new string:.

//: C03:StringIterators.cpp

#include

#include

#include

using namespace std;

int main() {

  string source("xxx");

  string s(source.begin(), source.end());

  assert(s == source);

} ///:~

The iterators are not restricted to begin( ) and end( ); you can increment, decrement, and add integer offsets to them, allowing you to extract a subset of characters from the source string.

C++ strings may not be initialized with single characters or with ASCII or other integer values. You can initialize a string with a number of copies of a single character, however.

//: C03:UhOh.cpp

#include

#include

using namespace std;

int main() {

  // Error: no single char inits

  //! string nothingDoing1('a');

  // Error: no integer inits

  //! string nothingDoing2(0x37);

  // The following is legal:

  string okay(5, 'a');

  assert(okay == string("aaaaa"));

} ///:~

<p>Operating on strings</p>
Перейти на страницу:

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

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

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

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

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

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

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

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