std::string
6 methodsThe C++ standard library string class, a specialization of std::basic_string for char.
std::string::size() const noexcept -> size_tReturns 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
| Name | Type | Description |
|---|---|---|
| s | const 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 -> stringReturns a substring starting at pos with length len (or to the end if npos).
Parameters
| Name | Type | Description |
|---|---|---|
| pos | size_t | Starting position (default 0). |
| len | size_t | Length 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_tSearches for the first occurrence of s starting at pos. Returns npos if not found.
Parameters
| Name | Type | Description |
|---|---|---|
| s | const string& | Substring to search for. |
| pos | size_t | Position 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()); // hellostd::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
| Name | Type | Description |
|---|---|---|
| pos | size_t | Start position of the portion to replace. |
| len | size_t | Number of characters to replace. |
| s | const string& | Replacement string. |
Returns
string&
Example
cpp
std::string s = "Hello, World";
s.replace(7, 5, "C++");
// s == "Hello, C++"