LIBRARY CLASSES FOR STRINGS

As I said in Chapter 4, the string header defines the string and wstring classes that represent character strings. Both are defined as instances of the basic_string<T> class template. The string class is defined as basic_string<char>, and wstring is defined as basic_string<wchar_t>, so the string class represents strings of characters of type char, and wstring represents strings of characters of type wchar_t.

These string types are much easier to use than null-terminated strings and bring with them a whole range of powerful functions. Because string and wstring are both instances of the basic_string<T> template they provide the same functionality, so I’ll only discuss the features and use in the context of the string type. The wstring type will work just the same, except that the strings contain Unicode character codes and you must use the L prefix for string literals in your code.

Creating String Objects

Creating string objects is very easy but you have a lot of choices as to how you do it. First, you can create and initialize a string object like this:

string sentence = "This sentence is false.";

The sentence object is initialized with the string literal that appears to the right of the assignment operator. You can also use functional notation:

string sentence("This sentence is false.");

A string object has no terminating null character, so the string length is the number of characters in the string, 23 in this instance. You can discover the length ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.