Wednesday, 8 June 2011
C++ Basics From H e r b S c h i l d t ' s C + + P r o g r a m m i n g C o o k b o o k
String Handling
There is almost always more than one way to do something in C++. This is one reason
why C++ is such a rich and powerful language. It lets the programmer choose the best
approach for the task at hand. Nowhere is this multifaceted aspect of C++ more evident
than in strings. In C++, strings are based on two separate but interrelated subsystems. One
type of string is inherited from C. The other is defined by C++. Together, they provide the
programmer with two different ways to think about and handle sequences of characters.
The first type of string supported by C++ is the null-terminated string. This is a char array
that contains the characters that comprise a string, followed by a null. The null-terminated
string is inherited from C and it gives you low-level control over string operations. As a
result, the null-terminated string offers a very efficient way in which to handle character
sequences. C++ also supports wide-character, null-terminated strings, which are arrays of
type wchar_t.
The second type of string is an object of type basic_string, which is a template class
defined by C++. Therefore, basic_string defines a unique type whose sole purpose is to
represent sequences of characters. Because basic_string defines a class type, it offers a highlevel
approach to working with strings. For example, it defines many member functions
that perform various string manipulations, and several operators are overloaded for string
operations. There are two specializations of basic_string that are defined by C++: string
and wstring. The string class operates on characters of type char, and wstring operates on
characters of type wchar_t. Thus, wstring encapsulates a wide-character string.
As just explained, both null-terminated strings and basic_string support strings of types
char and wchar_t. The main difference between strings based on char and those based on
wchar_t is the size of the character. Otherwise, the two types of strings are handled in
essentially the same way. For the sake of convenience and because char-based strings are, by
far, the most common, they are the type of strings used in the recipes in this chapter. However,
the same basic techniques can be adapted to wide-character strings with little effort.
The topic of C++ strings is quite large. Frankly, it would be easy to fill an entire book
with recipes about them. Thus, limiting the string recipes to a single chapter presented quite
a challenge. In the end, I selected recipes that answer common questions, illustrate key
aspects of each string type, or demonstrate general principles that can be adapted to a wide
variety of uses.
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment