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 (usestrcmp) vsstd::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).