<string>

The <string> header declares the class templates and functions that support the string and wstring types, which are specializations of the basic_string class template. The string types are easier to use and safer than C-style character arrays. Another important class template is char_traits, which describes a character type and is used throughout the standard library.

The complete declarations of the overloaded operators can be daunting to read. To help you, each function template declaration is followed by a comment that shows the equivalent declaration that uses the common typedefs for narrow characters (e.g., string instead of basic_string<charT, traits, Allocator>).

Example 13-37 shows a function that classifies a string as an identifier, integer, floating point, or other. The example demonstrates the use of the string class and several of its member functions.

Example 13-37. Classifying a string
#include <iostream> #include <string> enum kind { empty, ident, integer, floatingpt, error }; kind classify(const std::string& s) { using std::string; const string lower("abcdefghijklmnopqrstuvwxyz"); const string upper("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); const string letters = lower + upper + '_'; const string digits("0123456789"); const string identchars = letters + digits; if (s.empty( )) return empty; else if (letters.find_first_of(s[0]) != string::npos) { // Check for valid identifier. if (s.find_first_not_of(identchars, 1) == string::npos) return ident; else return error; } // ...

Get C++ In a Nutshell 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.