Skip to content

C++ <string> API

C++ std::string — a contiguous, growable sequence of chars with a rich member-function interface.

1 class · 6 methods

std::string

6 methods

The C++ standard library string class, a specialization of std::basic_string for char.

std::string::size() const noexcept -> size_t

Returns the number of characters in the string, not including the null terminator.

Returns

size_t

Example

cpp
#include <string>
#include <iostream>

int main() {
    std::string s = "hello";
    std::cout << s.size() << "\n";  // 5
}
std::string::append(const string& s) -> string&

Appends the given string to the end of this string.

Parameters

NameTypeDescription
sconst string&String to append.

Returns

string&

Example

cpp
std::string s = "Hello";
s.append(", World");
// s == "Hello, World"
std::string::substr(size_t pos = 0, size_t len = npos) const -> string

Returns a substring starting at pos with length len (or to the end if npos).

Parameters

NameTypeDescription
possize_tStarting position (default 0).
lensize_tLength of substring (default npos = to end).

Returns

string

Example

cpp
std::string s = "Hello, World";
std::string sub = s.substr(7, 5);  // "World"
std::string rest = s.substr(7);    // "World"
std::string::find(const string& s, size_t pos = 0) const -> size_t

Searches for the first occurrence of s starting at pos. Returns npos if not found.

Parameters

NameTypeDescription
sconst string&Substring to search for.
possize_tPosition to start searching from.

Returns

size_t

Example

cpp
std::string s = "Hello, World";
size_t pos = s.find("World");
if (pos != std::string::npos) {
    // found at pos == 7
}
std::string::c_str() const noexcept -> const char*

Returns a pointer to a null-terminated C string representation of the string's data.

Returns

const char*

Example

cpp
std::string s = "hello";
printf("%s\n", s.c_str());  // hello
std::string::replace(size_t pos, size_t len, const string& s) -> string&

Replaces the portion of the string starting at pos with length len by the string s.

Parameters

NameTypeDescription
possize_tStart position of the portion to replace.
lensize_tNumber of characters to replace.
sconst string&Replacement string.

Returns

string&

Example

cpp
std::string s = "Hello, World";
s.replace(7, 5, "C++");
// s == "Hello, C++"