Core Module
12 min forge

C++ Strings

Mastering the std::string class for powerful text manipulation.

C++ Strings

πŸ“˜ What is it

In C++, std::string is a class that represents a sequence of characters. It is much more powerful and safer than C-style character arrays (char*).

⚑ When to use

For any text processing, string concatenation, searching, and manipulation.

🧠 Time complexity

  • Access: $O(1)$
  • Concatenation: $O(N+M)$
  • Length: $O(1)$
  • Search: $O(N)$

πŸ’» Code example

cpp Standard
#include <string> std::string s = "Hello"; s += " World"; // Concatenation int len = s.length(); // 11 char first = s[0]; // 'H'

❌ Common mistakes

  • Using == to compare C-style strings (use strcmp) vs std::string (where == works perfectly).
  • Accessing indices out of bounds using [] (doesn't throw exception) instead of .at() (throws exception).
  • Inefficient string concatenation in loops (creates many temporary objects).