Lesson 212 +5 XP

<string> Member Functions Reference

<string> Member Functions Reference

The std::string class manages text for you: growth, storage, destruction, the whole package. Here are the member functions you'll need.

Size and capacity

FunctionExampleWhat it does
length()s.length()number of characters total
size()s.size()same as length(), same letters
capacity()s.capacity()characters the string can hold in its current memory
empty()s.empty()true if the string has zero characters
clear()s.clear()remove all characters, size becomes 0
reserve(n)s.reserve(30)pre-allocate memory for at least n chars
resize(n)s.resize(10)force the size to n, fill new chars with '\0'

Access a single character

FunctionExampleNotes
at(n)s.at(0)bounds-checked; throws out_of_range on bad index
operator[]s[0]no bounds check - faster, but your job to stay in range
front()s.front()first character
back()s.back()last character

Editing the text

FunctionExampleWhat it does
appends.append("word")add text to the end (same as +=)
inserts.insert(2, "XX")insert text at position 2
replaces.replace(3, 2, "YZ")replace 2 chars starting at index 3 with "YZ"
erases.erase(2, 3)remove 3 chars starting at index 2
push_backs.push_back('X')add one character at the end
pop_backs.pop_back()remove the last character (C++11)

Search and slicing

FunctionExampleWhat it returns
finds.find("needle")index of the first niche or npos if not found
substrs.substr(3, 2)a shorter string cut from the string

npos is a special "not found" size_t value. Always compare: if (s.find("x") != string::npos).

substr(3) without a length grabs the rest.

Comparing and converting

FunctionExampleWhat it does
compares.compare(t)<0 if smaller, 0 if equal, >0 if bigger (dictionary order)
c_str()s.c_str()C-style char pointer version (NUL-terminated, const)
data()s.data()pointer to the character data (no NUL guarantee before C++11)

Free functions for conversions

FunctionExampleWhat it does
to_stringto_string(42)turns a number into a string
stoistoi("42")converts a string to int
stodstod("3.14")converts a string to double
stolstol("123456")converts a string to long

These live in the std namespace too; you'll already have them after including <string>.

Notes

  • find returns string::npos (a huge number) when nothing is found - compare, don't assume.
  • at checks bounds and throws; [] is faster and trusts you.
  • substr creates a new string; it does not copy the original.
  • Strings auto-grow when you append during use - no manual resize needed.

TL;DR

  • Size: length()/size()/empty(); manage room with reserve()/resize().
  • Edit: append/insert/replace/erase/push_back/pop_back.
  • Find find + substr to locate and cut text.
  • Convert with to_string / stoi / stod.