C++ Strings Study Guide
1. String Fundamentals
What is a String?
A string is a sequence of characters
In C++, we primarily use std::string from the <string> header
Strings are mutable (can be modified after creation)
Internally implemented as dynamic arrays of characters
Basic Declaration and Initialization
cpp
#include <string>
using namespace std;
// Different ways to declare strings
string str1; // Empty string
string str2 = "Hello"; // Direct initialization
string str3("World"); // Constructor initialization
string str4 = str2; // Copy initialization
string str5(5, 'A'); // Initialize with 5 'A's: "AAAAA"
2. String Input/Output
Basic I/O
cpp
string name;
cout << "Enter name: ";
cin >> name; // Reads until whitespace
cout << "Hello " << name << endl;
// Reading entire line (including spaces)
string fullName;
getline(cin, fullName);
Important Notes
cin >> stops at whitespace
getline() reads entire line including spaces
Always clear input buffer when switching between cin >> and getline()
3. String Properties and Access
Size and Capacity
cpp
string str = "Hello World";
cout << str.length(); // 11
cout << str.size(); // 11 (same as length())
cout << str.capacity(); // Current allocated capacity
cout << str.max_size(); // Maximum possible size
Character Access
cpp
string str = "Hello";
char ch = str[2]; // 'l' - no bounds checking
char ch2 = str.at(2); // 'l' - with bounds checking
char first = str.front(); // 'H'
char last = str.back(); // 'o'
String State
cpp
string empty = "";
if (empty.empty()) { // Check if string is empty
cout << "String is empty";
}
4. String Modification Operations
Adding Content
cpp
string str = "Hello";
str += " World"; // Concatenation assignment
str.append(" !"); // Append method
str.push_back('?'); // Add single character at end
str.insert(5, " C++"); // Insert at position 5
Removing Content
cpp
string str = "Hello World";
str.pop_back(); // Remove last character
str.erase(5, 6); // Remove 6 chars starting at pos 5
str.erase(5); // Remove everything from pos 5 onwards
str.clear(); // Make string empty
Replacing Content
cpp
string str = "Hello World";
str.replace(6, 5, "C++"); // Replace 5 chars at pos 6 with "C++"
str.assign("New String"); // Replace entire string
5. String Search Operations
Finding Substrings
cpp
string text = "Hello World Hello";
size_t pos = text.find("Hello"); // Returns 0 (first occurrence)
size_t pos2 = text.find("Hello", 1); // Returns 12 (search from pos 1)
size_t pos3 = text.rfind("Hello"); // Returns 12 (last occurrence)
size_t pos4 = text.find("xyz"); // Returns string::npos if not found
// Always check for string::npos
if (pos != string::npos) {
cout << "Found at position: " << pos;
}
Finding Characters
cpp
string text = "Hello World";
size_t pos = text.find_first_of("aeiou"); // First vowel
size_t pos2 = text.find_last_of("aeiou"); // Last vowel
size_t pos3 = text.find_first_not_of("Helo"); // First char not in set
6. String Comparison
Comparison Operators
cpp
string str1 = "apple";
string str2 = "banana";
if (str1 == str2) { /* equal */ }
if (str1 != str2) { /* not equal */ }
if (str1 < str2) { /* lexicographically smaller */ }
if (str1 <= str2) { /* less than or equal */ }
Compare Method
cpp
string str1 = "apple";
string str2 = "banana";
int result = str1.compare(str2);
// result < 0: str1 < str2
// result = 0: str1 == str2
// result > 0: str1 > str2
7. Substring Operations
Extracting Substrings
cpp
string text = "Hello World";
string sub1 = text.substr(6); // "World" (from pos 6 to end)
string sub2 = text.substr(0, 5); // "Hello" (5 chars from pos 0)
string sub3 = text.substr(6, 3); // "Wor" (3 chars from pos 6)
8. String Conversion
String to Numbers
cpp
#include <string>
string numStr = "123";
int num = stoi(numStr); // String to int
long lnum = stol(numStr); // String to long
float fnum = stof(numStr); // String to float
double dnum = stod(numStr); // String to double
Numbers to String
cpp
int num = 123;
string str = to_string(num); // "123"
double pi = 3.14159;
string piStr = to_string(pi); // "3.141590"
9. String Iteration
Different Ways to Iterate
cpp
string str = "Hello";
// Method 1: Index-based
for (size_t i = 0; i < str.length(); i++) {
cout << str[i] << " ";
}
// Method 2: Range-based for loop (C++11)
for (char c : str) {
cout << c << " ";
}
// Method 3: Iterators
for (auto it = str.begin(); it != str.end(); ++it) {
cout << *it << " ";
}
// Method 4: Reverse iteration
for (auto it = str.rbegin(); it != str.rend(); ++it) {
cout << *it << " ";
}
10. Common String Algorithms
Reversing a String
cpp
string str = "Hello";
reverse(str.begin(), str.end()); // Requires <algorithm>
Sorting Characters
cpp
string str = "hello";
sort(str.begin(), str.end()); // Result: "ehllo"
Case Conversion
cpp
#include <algorithm>
#include <cctype>
string str = "Hello World";
// Convert to uppercase
transform(str.begin(), str.end(), str.begin(), ::toupper);
// Convert to lowercase
transform(str.begin(), str.end(), str.begin(), ::tolower);
11. Performance Considerations
String Concatenation
cpp
// Inefficient for multiple concatenations
string result = "";
for (int i = 0; i < 1000; i++) {
result += "a"; // Creates new string each time
}
// More efficient - reserve space
string result;
result.reserve(1000); // Reserve space upfront
for (int i = 0; i < 1000; i++) {
result += "a";
}
Memory Management
reserve() - allocates memory without changing size
resize() - changes both size and potentially capacity
shrink_to_fit() - reduces capacity to match size
12. Common Interview Problems
Pattern Matching
Check if string is palindrome
Find longest common subsequence
Pattern searching algorithms
String Manipulation
Remove duplicates
String compression
Anagram checking
String rotation problems
13. Best Practices
1. Always check bounds when using at() method
2. Check for string::npos when using find operations
3. Use empty() instead of size() == 0
4. Reserve memory for large string operations
5. Use range-based loops when possible for cleaner code
6. Be careful with character encoding (ASCII vs UTF-8)
14. Common Pitfalls
1. Index out of bounds - str[str.size()] is undefined behavior
2. Comparing with string::npos incorrectly
3. Not clearing input buffer between different input methods
4. Assuming null termination - C++ strings handle this internally
5. Performance issues with repeated concatenation
15. Practice Problems
Beginner Level
1. Write a function to count vowels in a string
2. Check if a string is a palindrome
3. Remove all spaces from a string
4. Find the first non-repeating character
Intermediate Level
1. Implement string compression (aaabbc → a3b2c1)
2. Check if two strings are anagrams
3. Find all permutations of a string
4. Implement basic string matching algorithm
Advanced Level
1. Longest palindromic substring
2. Edit distance between two strings
3. Pattern matching with wildcards
4. String matching with regular expressions
Quick Reference Card
Operation Syntax Time Complexity
Access str[i] or str.at(i) O(1)
Length str.size() or str.length() O(1)
Append str += "text" O(n) amortized
Insert str.insert(pos, "text") O(n)
Find str.find("pattern") O(nm) worst case
Substring str.substr(pos, len) O(n)
Compare str1.compare(str2) O(n)
Remember: Practice is key to mastering strings in C++. Start with basic operations and gradually work
your way up to more complex algorithms!