C++'s built-in string type. Far safer and more capable than C-style char* arrays. Automatically manages memory.
Include: #include <string> | Namespace: std | Compile: g++ -Wall -std=c++17 ...
| Name | Type / Signature | Description |
|---|---|---|
| std::string | class | Dynamic character string class |
| s.size() | size_t | Number of characters |
| s.length() | size_t | Same as size() |
| s.empty() | bool | True if string has no characters |
| s.clear() | void | Erase all characters |
| s.append(t) | string & | Append string t to end |
| s += t | string & | Append string or char t |
| s.push_back(c) | void | Append single character c |
| s.pop_back() | void | Remove last character (C++11) |
| s.substr(p,n) | string | Return substring starting at p, length n |
| s.find(t) | size_t | Return position of first occurrence, or npos |
| s.rfind(t) | size_t | Return position of last occurrence |
| s.replace(p,n,t) | string & | Replace n chars at position p with t |
| s.insert(p,t) | string & | Insert string t at position p |
| s.erase(p,n) | string & | Erase n chars at position p |
| s.compare(t) | int | Lexicographic compare; 0=equal |
| s.at(i) | char & | Access char at index i with bounds check |
| s[i] | char & | Access char at index i (no bounds check) |
| s.front() | char & | Reference to first character |
| s.back() | char & | Reference to last character |
| s.c_str() | const char * | Return C-style null-terminated pointer |
| std::to_string(n) | string | Convert numeric type n to std::string (C++11) |
| std::stoi(s) | int | Parse string to int (C++11) |
| std::stol(s) | long | Parse string to long |
| std::stod(s) | double | Parse string to double |
| string::npos | static const size_t | Returned by find() when not found |
Copy, save as demo.cpp, and compile with the command at the bottom.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s = "Hello, C++!";
cout << "String : " << s << "\n";
cout << "Length : " << s.size() << "\n";
cout << "Substr : " << s.substr(7, 3) << "\n";
size_t pos = s.find("C++");
if (pos != string::npos)
cout << "Found C++ at index " << pos << "\n";
s.replace(pos, 3, "World");
cout << "Replaced : " << s << "\n";
string up = s;
transform(up.begin(), up.end(), up.begin(), ::toupper);
cout << "Upper : " << up << "\n";
cout << "pi_str = " << to_string(3.14159) << "\n";
return 0;
}
// Compile: g++ -Wall -std=c++17 -o string_demo string_demo.cpp