C++ - Strings (Basics)

Overview

Estimated time: 35–45 minutes

Work with std::string: build, combine, measure length, access characters, and iterate safely.

Learning Objectives

  • Create and concatenate strings.
  • Get length, index safely, and iterate characters.

Prerequisites

Create and concatenate

#include <string>
#include <iostream>
int main(){
  std::string a = "Hello";
  std::string b = a + ", world";
  std::cout << b << "!\n";
}

Length and indexing

std::string s = "abc";
std::cout << s.size(); // 3
char c = s[0];        // 'a' (no bounds check)

Iteration

for (char ch : s) { /* ... */ }

Common Pitfalls

  • Using operator[] out of bounds is undefined; prefer at() if you need checking.
  • Mixing std::string with C strings without care—convert explicitly when needed.