C++ ยท Chapter 11 of 49

C++ Strings

The `std::string` class (from `<string>`) represents text and supports concatenation with `+`, comparison with `==`, and indexing with `[]`. It automatically manages memory, growing as needed.

Strings are zero-indexed, so `s[0]` is the first character. C++ also has C-style character arrays, but std::string is safer and easier for most tasks.

Creating and combining strings

You can concatenate strings with `+`, or append with `+=`. Comparing two strings with `==` checks their content, not their memory address.

Accessing characters

`s[i]` or `s.at(i)` returns the character at index i. `.at()` throws an exception on out-of-range access, while `[]` has undefined behaviour.

Example 1 (cpp)
std::string first = "Hello";
std::string full = first + ", World!";
std::cout << full;
Output
Hello, World!

+ concatenates two strings.

Example 2 (cpp)
std::string s = "cpp";
std::cout << s[0] << s.length();
Output
c3

Indexing gives a single character; length() gives the size.

Key points

  • std::string needs #include <string>.
  • + concatenates; += appends in place.
  • Strings are zero-indexed via [] or .at().
  • == compares string content.
๐Ÿ’ก Note: .at() is safer than [] because it throws std::out_of_range instead of undefined behaviour.

๐Ÿ“ Quick Quiz

1. Which operator concatenates two strings?

2. What is the index of the first character?

3. Which method throws an exception for an invalid index?