Thinking in C++ - Practical Programming (2024)

Â

Â

Thinking in C++ Vol 2 - Practical Programming
PrevHomeNext

Creating and initializing C++ strings

Creating and initializing strings is a straightforwardproposition and fairly flexible. In the SmallString.cpp example below,the first string, imBlank, is declared but contains no initialvalue. Unlike a C char array, which would contain a random andmeaningless bit pattern until initialization, imBlank does containmeaningful information. This string object is initialized to hold nocharacters and can properly report its zero length and absence of dataelements using class member functions.

The next string, heyMom, is initialized by theliteral argument Where are my socks? This form of initialization uses aquoted character array as a parameter to the string constructor. Bycontrast, standardReply is simply initialized with an assignment. Thelast string of the group, useThisOneAgain, is initialized using anexisting C++ string object. Put another way, this example illustratesthat string objects let you do the following:

ÂÂÂÂÂÂCreate an empty string and defer initializing it withcharacter data.

ÂÂÂÂÂÂInitialize a string by passing a literal, quoted characterarray as an argument to the constructor.

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

ÂÂÂÂÂÂUse one string to initialize another.

//: C03:SmallString.cpp

#include <string>

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 stringinitialization, but variations offer more flexibility and control. You can dothe 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 illustratesthese features:

//: C03:SmallString2.cpp

#include <string>

#include <iostream>

using namespace std;

Â

int main() {

string s1("What is the sound of one clamnapping?");

string s2("Anything worth doing is worthoverdoing.");

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 many different things:

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 toselect 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, sothis 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 doingwith Elvis in a UFO?

Â

Notice the final line of the example. C++ allows stringinitialization techniques to be mixed in a single statement, a flexible andconvenient feature. Also notice that the last initializer copies just onecharacter from the source string.

Another slightly more subtle initialization techniqueinvolves the use of the string iterators string::begin(Â)and string::end(Â). This technique treats a string like a containerobject (which you ve seen primarily in the form of vector so far you llsee many more containers in Chapter 7), which uses iterators to indicatethe start and end of a sequence of characters. In this way you can hand a stringconstructor two iterators, and it copies from one to the other into the new string:

//: C03:StringIterators.cpp

#include <string>

#include <iostream>

#include <cassert>

using namespace std;

Â

int main() {

string source("xxx");

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

assert(s == source);

} ///:~

Â

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

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

//: C03:UhOh.cpp

#include <string>

#include <cassert>

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"));

} ///:~

Â

The first argument indicates the number of copies of thesecond argument to place in the string. The second argument can only be asingle char, not a char array.

Thinking in C++ Vol 2 - Practical Programming
PrevHomeNext

Â
Thinking in C++ - Practical Programming (2024)
Top Articles
Latest Posts
Article information

Author: Maia Crooks Jr

Last Updated:

Views: 5598

Rating: 4.2 / 5 (63 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Maia Crooks Jr

Birthday: 1997-09-21

Address: 93119 Joseph Street, Peggyfurt, NC 11582

Phone: +2983088926881

Job: Principal Design Liaison

Hobby: Web surfing, Skiing, role-playing games, Sketching, Polo, Sewing, Genealogy

Introduction: My name is Maia Crooks Jr, I am a homely, joyous, shiny, successful, hilarious, thoughtful, joyous person who loves writing and wants to share my knowledge and understanding with you.