std::string (C++)

std::string is the C++ standard library type for text. It stores a sequence of characters and, unlike C-style char arrays, manages its own memory and can grow or shrink automatically.

C++

You need to #include <string> to use it. Strings can be joined with +, compared with ==, and indexed with [] to read individual characters.

Useful members include .length() (or .size()), .substr(), and .find(). std::string is far safer and easier than the old C-style strings.

Syntax

std::string name = "text";

Examples

C++

#include <iostream>
#include <string>

int main() {
    std::string first = "Hello";
    std::string greeting = first + ", world";
    std::cout << greeting << " (" << greeting.length() << ")" << std::endl;
    return 0;
}

Output:

Hello, world (12)

Learn it in a lesson

See also

Back to the Dictionary