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

string fourth_date {"Hank's Fine Eats"};

Assignment, Concatenation, and Appending

The string class makes some operations simpler than is the case for arrays. For example, you can’t simply assign one array to another. But you can assign one string object to another:

char charr1[20];            // create an empty array

char charr2[20] = "jaguar"; // create an initialized array

string str1;                // create an empty string object

string str2 = "panther";    // create an initialized string

charr1 = charr2;            // INVALID, no array assignment

str1 = str2;                // VALID, object assignment ok

The string class simplifies combining strings. You can use the + operator to add two string objects together and the += operator to tack on a string to the end of an existing string object. Continuing with the preceding code, we have the following possibilities:

string str3;

str3 = str1 + str2;         // assign str3 the joined strings

str1 += str2;               // add str2 to the end of str1

Listing 4.8 illustrates these usages. Note that you can add and append C-style strings as well as string objects to a string object.

Listing 4.8. strtype2.cpp

// strtype2.cpp –- assigning, adding, and appending

#include

#include                // make string class available

int main()

{

    using namespace std;

    string s1 = "penguin";

    string s2, s3;

    cout << "You can assign one string object to another: s2 = s1\n";

    s2 = s1;

    cout << "s1: " << s1 << ", s2: " << s2 << endl;

    cout << "You can assign a C-style string to a string object.\n";

    cout << "s2 = \"buzzard\"\n";

    s2 = "buzzard";

    cout << "s2: " << s2 << endl;

    cout << "You can concatenate strings: s3 = s1 + s2\n";

    s3 = s1 + s2;

    cout << "s3: " << s3 << endl;

    cout << "You can append strings.\n";

    s1 += s2;

    cout <<"s1 += s2 yields s1 = " << s1 << endl;

    s2 += " for a day";

    cout <<"s2 += \" for a day\" yields s2 = " << s2 << endl;

    return 0;

}

Recall that the escape sequence \" represents a double quotation mark that is used as a literal character rather than as marking the limits of a string. Here is the output from the program in Listing 4.8:

You can assign one string object to another: s2 = s1

s1: penguin, s2: penguin

You can assign a C-style string to a string object.

s2 = "buzzard"

s2: buzzard

You can concatenate strings: s3 = s1 + s2

s3: penguinbuzzard

You can append strings.

s1 += s2 yields s1 = penguinbuzzard

s2 += " for a day" yields s2 = buzzard for a day

More string Class Operations

Even before the string class was added to C++, programmers needed to do things like assign strings. For C-style strings, they used functions from the C library for these tasks. The cstring header file (formerly string.h) supports these functions. For example, you can use the strcpy() function to copy a string to a character array, and you can use the strcat() function to append a string to a character array:

strcpy(charr1, charr2);  // copy charr2 to charr1

strcat(charr1, charr2);  // append contents of charr2 to char1

Listing 4.9 compares techniques used with string objects with techniques used with character arrays.

Listing 4.9. strtype3.cpp

// strtype3.cpp -- more string class features

#include

#include                // make string class available

#include               // C-style string library

int main()

{

    using namespace std;

    char charr1[20];

    char charr2[20] = "jaguar";

    string str1;

    string str2 = "panther";

    // assignment for string objects and character arrays

    str1 = str2;                // copy str2 to str1

    strcpy(charr1, charr2);     // copy charr2 to charr1

    // appending for string objects and character arrays

    str1 += " paste";           // add paste to end of str1

    strcat(charr1, " juice");   // add juice to end of charr1

    // finding the length of a string object and a C-style string

    int len1 = str1.size();     // obtain length of str1

    int len2 = strlen(charr1);  // obtain length of charr1

    cout << "The string " << str1 << " contains "

         << len1 << " characters.\n";

    cout << "The string " << charr1 << " contains "

         << len2 << " characters.\n";

    return 0;

}

Here is the output:

The string panther paste contains 13 characters.

The string jaguar juice contains 12 characters.

The syntax for working with string objects tends to be simpler than using the C string functions. This is especially true for more complex operations. For example, the C library equivalent of

str3 = str1 + str2;

is this:

strcpy(charr3, charr1);

strcat(charr3, charr2);

Furthermore, with arrays, there is always the danger of the destination array being too small to hold the information, as in this example:

char site[10] = "house";

strcat(site, " of pancakes");  // memory problem

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

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

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

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

Все жанры