Skip to content
RobStewart edited this page May 15, 2013 · 2 revisions

There are two principal types of strings in C++: the null terminated sequence of characters, as inherited from C, and the std::basic_string class template. Plenty of material can be found on using the former. We will focus, here, on the latter.

std::string is a typedef, in the namespace, for (simplifying) std::basic_string<char>. There are strings with other character types, too, but we refer to std::string in this Wiki for simplicity. The definition of std::basic_string, and the various typedefs, are in the <string> header. The class manages memory for the contents it holds, including growing as needed, knows the length of the character sequence, and more. Characters are put into strings via string literals or by adding characters.

A string literal is a sequence of characters delimited by quotation marks: "This is a string literal". The characters that may appear in a string literal depend upon the However, C++11 offers more options on what can be put in a string literal or how it is interpreted. For example, preceding it with R forms a raw string literal, which tells the compiler to ignore escape sequences in the string. UTF-8 string literals are formed by prefixing the string literal with u8, as in u8"This is a UTF-8 string". Other prefixes are available: u8R, u, uR, U, UR, L, and LR. u makes the characters be of type char16_t, U makes them char32_t, and L makes them wchar_t.

There is a special, nested value in each std::basic_string specialization, called npos. It means no position, and is used to indicate a don't care value, not found, etc. in numerous member functions. Thus, std::string::npos can mean no length, not found, etc.

Clone this wiki locally