C++: C++ string
Last updated: 2026-08-26
C-style strings (character arrays) are cumbersome to use and prone to bugs (buffer overflows, forgetting
\0).C++ provides the string class — encapsulating strings into objects, making them safe and convenient to use.
1. What Is string?
(1) 1.1 Real-Life Analogy
| Real-Life Example | Program Equivalent |
|---|---|
| You have a backpack that you can put things into | A string object |
| The backpack can automatically expand (swap for a bigger one when full) | string dynamically manages memory |
| The backpack has multiple pockets for easy access | string's member functions |
Advantages of string:
- No need to manage memory — automatic allocation and deallocation
- No need to worry about
\0— the null terminator is handled automatically - Powerful functionality — concatenation, searching, and replacement are all convenient
(2) 1.2 Why Use string?
Using C-style strings (tedious):
▶ Example 2: Code Example (Difficulty ⭐)
#include <iostream>
#include <cstring>
int main() {
char greeting[50] = "Hello, ";
char name = "MOTO";
std::strcat(greeting, name); // Have to worry about array size
std::cout << greeting << std::endl;
return 0;
}
Output:
(program output)
Using string (simple):
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello, ";
std::string name = "MOTO";
greeting += name; // Automatic concatenation, no need to worry about memory
std::cout << greeting << std::endl;
return 0;
}
2. Declaring and Initializing string
(1) 2.1 Basic Usage
#include <iostream>
#include <string>
int main() {
// Method 1: Direct initialization
std::string s1 = "Hello";
// Method 2: Using constructor
std::string s2("World");
// Method 3: Repeat a character
std::string s3(5, '*'); // "*****"
std::cout << s1 << " " << s2 << " " << s3 << std::endl;
return 0;
}
💡 Key Point: You must #include <string> to use string.
3. Common string Operations
(1) 3.1 Concatenating Strings (+ and +=)
#include <iostream>
#include <string>
int main() {
std::string firstName = "MOTO";
std::string lastName = "Zhang";
// Method 1: Using +
std::string fullName1 = firstName + " " + lastName;
std::cout << fullName1 << std::endl; // MOTO Zhang
// Method 2: Using +=
std::string fullName2 = firstName;
fullName2 += " ";
fullName2 += lastName;
std::cout << fullName2 << std::endl; // MOTO Zhang
return 0;
}
(2) 3.2 Getting the Length (length and size)
#include <iostream>
#include <string>
int main() {
std::string name = "MOTO";
std::cout << "name: " << name << std::endl;
std::cout << "length(): " << name.length() << std::endl; // 4
std::cout << "size(): " << name.size() << std::endl; // 4
return 0;
}
💡 Tip: length() and size() are exactly the same — use either one.
(3) 3.3 Accessing Individual Characters ([] and at)
#include <iostream>
#include <string>
int main() {
std::string name = "MOTO";
// Method 1: Using []
std::cout << name[0] << std::endl; // M
name[0] = 'm'; // Can modify
// Method 2: Using at() (checks bounds)
std::cout << name.at(1) << std::endl; // o
// name.at(10); // ❌ Will throw exception (safer than [])
return 0;
}
💡 Difference:
name[i]— No bounds checking, more efficientname.at(i)— Bounds checking, safer but slightly slower
4. Common string Member Functions
(1) 4.1 Finding a Substring (find)
#include <iostream>
#include <string>
int main() {
std::string text = "Hello, World!";
// Find substring
size_t pos = text.find("World");
if (pos != std::string::npos) {
std::cout << "Found \"World\",Position: " << pos << std::endl; // 7
} else {
std::cout << "Not Found" << std::endl;
}
return 0;
}
💡 Tip: If not found, find() returns std::string::npos (typically the unsigned version of -1).
(2) 4.2 Extracting a Substring (substr)
#include <iostream>
#include <string>
int main() {
std::string email = "moto@example.com";
// Extract substring: starting at position 0, take 4 characters
std::string user = email.substr(0, 4);
std::cout << "Username: " << user << std::endl; // moto
// Extract substring: starting at position 5, take to the end
std::string domain = email.substr(5);
std::cout << "Domain: " << domain << std::endl; // example.com
return 0;
}
(3) 4.3 Replacing a Substring (replace)
#include <iostream>
#include <string>
int main() {
std::string text = "Hello, World!";
// Replace: starting at position 7, 5 characters, replace with "C++"
text.replace(7, 5, "C++");
std::cout << text << std::endl; // Hello, C++!
return 0;
}
5. Input and Output with string
(1) 5.1 Reading with cin (Stops at Spaces)
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "Please enter your name: ";
std::cin >> name; // ⚠️ Stops at spaces
std::cout << "Hello," << name << "!" << std::endl;
return 0;
}
Execution Result:
Please enter your name: MOTO Zhang
Hello,MOTO! ← Only read "MOTO"
(2) 5.2 Reading a Full Line with getline (Recommended)
#include <iostream>
#include <string>
int main() {
std::string fullName;
std::cout << "Please enter your full name: ";
std::getline(std::cin, fullName); // ✅ Reads the entire line (including spaces)
std::cout << "Hello," << fullName << "!" << std::endl;
return 0;
}
Execution Result:
Please enter your full name: MOTO Zhang
Hello,MOTO Zhang! ← Read completely
💡 Key Point: If you used cin >> before, remember to add cin.ignore() to discard the newline character!
6. Practice: Simple Text Processing
▶ Example 1: Counting Words (Difficulty ⭐⭐)
#include <iostream>
#include <string>
#include <sstream> // For stringstream
int main() {
std::string line;
std::cout << "Please enter a line of text: ";
std::getline(std::cin, line);
// Use stringstream to split words
std::istringstream ss(line);
std::string word;
int count = 0;
while (ss >> word) {
count++;
}
std::cout << "Word count: " << count << std::endl;
return 0;
}
Output:
Please enter a line of text:
Word count:
Execution Result:
Please enter a line of text: Hello World, this is C++!
Word count: 5
7. Common Mistakes
(1) 7.1 Forgetting #include <string>
Error Example:
#include <iostream> // ❌ Forgot to include string
int main() {
std::string name = "MOTO"; // ❌ Compile error
return 0;
}
Fix: Add #include <string>.
(2) 7.2 Using cin >> to Read Strings with Spaces
Error Example:
#include <iostream>
#include <string>
int main() {
std::string address;
std::cout << "Please enter your address: ";
std::cin >> address; // ❌ Stops at spaces
std::cout << "Address: " << address << std::endl;
return 0;
}
Fix: Use std::getline().
❓ FAQ
std::stringstream or std::string::reserve() to pre-allocate space.▶ Example 3: String Concatenation and Searching (Difficulty ⭐)
#include <iostream>
#include <string>
int main() {
std::string s1 = "Hello";
std::string s2 = "World";
std::string s3 = s1 + " " + s2;
std::cout << "Concatenation result: " << s3 << std::endl;
size_t pos = s3.find("World");
if (pos != std::string::npos) {
std::cout << "Found World at position: " << pos << std::endl;
}
return 0;
}
Output:
Concatenation result: Hello World
Found World at position: 6
std::string supports + for concatenation, and find() returns the position or npos (not found).
📖 Summary
- string is C++'s string class, safer and easier to use than C-style strings
- Must
#include <string> - Common operations:
+/+=concatenation,length()/size()for length,find()for searching,substr()for extracting substrings - Use
std::getline()to read a full line stringautomatically manages memory — no need to worry about buffer overflow
📝 Exercises
-
Basic (Difficulty ⭐): Write a program that lets the user input two strings, concatenates them, and outputs the result.
-
Intermediate (Difficulty ⭐⭐): Write a program that lets the user input a string and counts how many digit characters ('0'-'9') it contains.
-
Challenge (Difficulty ⭐⭐⭐): Write a program that implements a "simple student information management system":
-
Use
stringto store name, student ID, and major -
Implement functionality for adding, searching, and displaying all student information
-
(Optional) Save data to a file
- std::string is the C++ standard library string, with automatic memory management
- string supports + concatenation, == comparison, [] subscript access
- Common methods: length/size/substr/find/append
- string and C-style string interop: c_str()
- Be aware of buffer issues when mixing getline and cin >> for input
8. 🚀 Next Steps
Now that you've learned string, let's move on to Structs (Lesson 20) — combining multiple variables of different types into a single unit, a precursor to "classes"!