· Create an empty stringand defer initializing it with character data.
· Initialize a stringby passing a literal, quoted character array as an argument to the constructor.
· Initialize a stringusing the equal sign ( =).
· Use one stringto 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 stringinitialization, but variations offer more flexibility and control. You can do the following:
Use a portion of either a C chararray or a C++ string.
Combine different sources of initialization data using operator+.
Use the stringobject’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 stringmember 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 stringinitialization 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 stringiterators string::begin( )and string::end( ).This technique treats a stringlike a container object (which you’ve seen primarily in the form of vectorso 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 stringconstructor 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"));
} ///:~
If you’ve programmed in C, you are accustomed to the convenience of a large family of functions for writing, searching, modifying, and copying chararrays. However, there are two unfortunate aspects of the Standard C library functions for handling chararrays. First, there are two loosely organized families of them: the "plain" group, and the ones that require you to supply a count of the number of characters to be considered in the operation at hand. The roster of functions in the C chararray handling library shocks the unsuspecting user with a long list of cryptic, mostly unpronounceable names. Although the kinds and number of arguments to the functions are somewhat consistent, to use them properly you must be attentive to details of function naming and parameter passing .
The second inherent trap of the standard C chararray tools is that they all rely explicitly on the assumption that the character array includes a null terminator. If by oversight or error the null is omitted or overwritten, there’s little to keep the C chararray handling functions from manipulating the memory beyond the limits of the allocated space, sometimes with disastrous results .
C++ provides a vast improvement in the convenience and safety of stringobjects. For purposes of actual string handling operations, there are about the same number of distinct member function names in the stringclass as there are functions in the C library, but because of overloading there is much more functionality. Coupled with sensible naming practices and the judicious use of default arguments, these features combine to make the stringclass much easier to use than the C library .
Appending, inserting, and concatenating strings
One of the most valuable and convenient aspects of C++ strings is that they grow as needed, without intervention on the part of the programmer. Not only does this make string-handling code inherently more trustworthy, it also almost entirely eliminates a tedious "housekeeping" chore—keeping track of the bounds of the storage in which your strings live. For example, if you create a string object and initialize it with a string of 50 copies of ‘X’, and later store in it 50 copies of "Zowie", the object itself will reallocate sufficient storage to accommodate the growth of the data. Perhaps nowhere is this property more appreciated than when the strings manipulated in your code change size and you don’t know how big the change is. Appending, concatenating, and inserting strings often give rise to this circumstance, but the string member functions append( )and insert( )transparently reallocate storage when a string grows .
//: C03:StrSize.cpp
#include
#include
using namespace std;
int main() {
string bigNews("I saw Elvis in a UFO. ");
cout << bigNews << endl;
// How much data have we actually got?
cout << "Size = " << bigNews.size() << endl;
Читать дальше