← C++ Index

🔤 <string> — std::string — Dynamic String Class

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 ...

📋 Classes, Functions & Symbols

NameType / SignatureDescription
std::stringclassDynamic character string class
s.size()size_tNumber of characters
s.length()size_tSame as size()
s.empty()boolTrue if string has no characters
s.clear()voidErase all characters
s.append(t)string &Append string t to end
s += tstring &Append string or char t
s.push_back(c)voidAppend single character c
s.pop_back()voidRemove last character (C++11)
s.substr(p,n)stringReturn substring starting at p, length n
s.find(t)size_tReturn position of first occurrence, or npos
s.rfind(t)size_tReturn 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)intLexicographic 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)stringConvert numeric type n to std::string (C++11)
std::stoi(s)intParse string to int (C++11)
std::stol(s)longParse string to long
std::stod(s)doubleParse string to double
string::nposstatic const size_tReturned by find() when not found

💡 Example Program

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

← <iostream>  |  🏠 Index  |  <vector> →