std:string

suggest change

Introduction

Strings are objects that represent sequences of characters. The standard string class provides a simple, safe and versatile alternative to using explicit arrays of chars when dealing with text and other sequences of characters. The C++ string class is part of the std namespace and was standardized in 1998.

Syntax

std::string s;

std::string s(“Hello”);

std::string s = “Hello”;

std::string s1(“Hello”);

std::string s2(s1);

std::string s1(“Hello”);

std::string s2(s1, 0, 4); // Copy 4 characters from position 0 of s1 into s2

std::string s1(“Hello World”);

std::string s2(s1, 5); // Copy first 5 characters of s1 into s2

std::string s(5, ‘a’); // s contains aaaaa

std::string s1(“Hello World”);

std::string s2(s1.begin(), s1.begin()+5); // Copy first 5 characters of s1 into s2

Remarks

Before using std::string, you should include the header string, as it includes functions/operators/overloads that other headers (for example iostream) do not include.

Using const char* constructor with a nullptr leads to undefined behavior.

std::string oops(nullptr);
std::cout << oops << "\n";

The method at throws an std::out_of_range exception if index >= size().

The behavior of operator[] is a bit more complicated, in all cases it has undefined behavior if index > size(), but when index == size():

  1. On a non-const string, the behavior is undefined;
  2. On a const string, a reference to a character with value CharT() (the null character) is returned.
  3. A reference to a character with value CharT() (the null character) is returned.
  4. Modifying this reference is undefined behavior.

Since C++14, instead of using "foo", it is recommended to use "foo"s, as s is a user-defined literal suffix, which converts the const char* "foo" to std::string "foo".

Note: you have to use the namespace std::string_literals or std::literals to get the literal s.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


std::string:
* std:string

Table Of Contents
8 Arrays
11 Loops
20 std::string
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype