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:

  1. No need to manage memory — automatic allocation and deallocation
  2. No need to worry about \0 — the null terminator is handled automatically
  3. 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 ⭐)

TEXT 📖 Display only
#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:

TEXT 📖 Display only
(program output)

Using string (simple):

CPP
#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

CPP
#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 +=)

CPP
#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)

CPP
#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)

CPP
#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:



4. Common string Member Functions

(1) 4.1 Finding a Substring (find)

CPP
#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)

CPP
#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)

CPP
#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)

CPP
#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:

TEXT 📖 Display only
Please enter your name: MOTO Zhang
Hello,MOTO! ← Only read "MOTO"
CPP
#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:

TEXT 📖 Display only
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 ⭐⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Please enter a line of text: 
Word count: 

Execution Result:

TEXT 📖 Display only
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:

CPP
#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:

CPP
#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

Q Why is my string concatenation slow?
A Each concatenation may reallocate memory. If you're concatenating in a loop, use std::stringstream or std::string::reserve() to pre-allocate space.
Q Can string store Chinese characters?
A Yes! But make sure the source file is UTF-8 encoded and the terminal supports UTF-8. > > std::string name = "Zhang San"; // Can store Chinese > std::cout << name << std::endl; >

▶ Example 3: String Concatenation and Searching (Difficulty ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Concatenation result: Hello World
Found World at position: 6
💡 Tip: C++ std::string supports + for concatenation, and find() returns the position or npos (not found).


📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Write a program that lets the user input two strings, concatenates them, and outputs the result.

  2. Intermediate (Difficulty ⭐⭐): Write a program that lets the user input a string and counts how many digit characters ('0'-'9') it contains.

  3. Challenge (Difficulty ⭐⭐⭐): Write a program that implements a "simple student information management system":

  4. Use string to store name, student ID, and major

  5. Implement functionality for adding, searching, and displaying all student information

  6. (Optional) Save data to a file


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"!

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏