In the world of C++ programming, string manipulation is a fundamental skill for every programmer. Whether handling user input, file operations, or network communication, strings play a crucial role. This article will guide you through the comprehensive aspects of C++ string handling, building a complete knowledge system.
🎯 Three Main Text Data Types: Understanding the Basics
1.1 Three Representations
char ch; // Single character
char c[100]; // Character array (C-style string)
string str; // String object (C++ style)
1.2 Core Differences
| Type | Characteristics | Applicable Scenarios |
|---|---|---|
| Character | The most basic text unit, occupies 1 byte | Single character processing |
| Character Array | A character sequence ending with <span>\0</span>, requires manual memory management |
C language compatibility, performance-sensitive scenarios |
| String Object | C++ standard library class, automatically manages memory, rich functionality | Most modern C++ applications |
🔍 Character Handling Functions: Building a Strong Foundation
2.1 Character Judgment Functions
islower(ch) // Check if it is a lowercase letter → 'a'-'z'
isupper(ch) // Check if it is an uppercase letter → 'A'-'Z'
2.2 Character Conversion Functions
tolower(ch) // Convert uppercase to lowercase: 'A'→'a'
toupper(ch) // Convert lowercase to uppercase: 'a'→'A'
Application Scenarios: User input validation, case-insensitive comparison, data normalization.
📋 C-Style String Functions: Traditional but Important
3.1 Common Function Quick Reference
| Function Format | Function Description | Notes |
|---|---|---|
<span>strcat(dest, src)</span> |
String concatenation | dest must have enough space |
<span>strcpy(dest, src)</span> |
String copy | dest must have enough space |
<span>strcmp(str1, str2)</span> |
String comparison | Returns 0 if equal |
<span>strlen(str)</span> |
String length | Does not include<span>\0</span> |
<span>strlwr(str)</span> |
Convert to lowercase | Modifies in place |
<span>strupr(str)</span> |
Convert to uppercase | Modifies in place |
<span>strstr(haystack, needle)</span> |
Find substring | Returns pointer or NULL |
3.2 Practical Example
char name[20] = "Hello";
char world[] = " World";
strcat(name, world); // name becomes "Hello World"
int len = strlen(name); // len = 11
int cmp = strcmp("abc", "abd"); // cmp is negative
🚀 C++ String Class: Modern String Handling
4.1 Creation and Initialization
string s1; // Empty string
string s2 = "Hello"; // Literal initialization
string s3 = s2; // Copy initialization
string s4(5, 'A'); // "AAAAA"
4.2 Operator Overloading: Making Code More Intuitive
string s1 = "Hello", s2 = "World";
// Concatenation operation
string s3 = s1 + " " + s2; // "Hello World"
s1 += "!"; // s1 becomes "Hello!"
// Comparison operation (supports all comparison operators)
if (s1 == s2) { /* equal */ }
if (s1 < s2) { /* less than */ }
// Access operation
char first = s1[0]; // 'H'
s1[0] = 'h'; // Modify to "hello!"
4.3 Core Member Functions Explained
🔧 Capacity Related
string s = "Hello";
int len1 = s.length(); // 5
int len2 = s.size(); // 5 (same as length())
bool empty = s.empty(); // false
🔍 Searching and Locating
string text = "Hello World";
// Forward search
size_t pos1 = text.find('o'); // 4
size_t pos2 = text.find("World"); // 6
size_t pos3 = text.find('x'); // string::npos (not found)
// Backward search
size_t pos4 = text.rfind('o'); // 7
// Find any character
size_t pos5 = text.find_first_of("aeiou"); // 1 (first vowel 'e')
✂️ Substring Operations
string s = "Hello World";
string sub1 = s.substr(6); // "World" (from position 6 to end)
string sub2 = s.substr(0, 5); // "Hello" (5 characters from 0)
✏️ Modification Operations
string s = "Hello";
// Adding content
s.append(" World"); // "Hello World"
s.push_back('!'); // "Hello World!"
// Inserting content
s.insert(5, " dear"); // "Hello dear World!"
// Replacing content
s.replace(6, 4, "wonderful"); // "Hello dear wonderful!"
// Deleting content
s.erase(5, 5); // "Hello wonderful!"
📊 Data Access
string s = "Hello";
const char* cstr = s.c_str(); // Get C-style string
const char* data = s.data(); // Get data pointer
⌨️ String Input and Output: Correctly Handling User Input
5.1 C-Style Input Functions
char buffer[100];
// Safety recommendation
fgets(buffer, sizeof(buffer), stdin); // Read a line, including newline character
// Not recommended (deprecated)
gets(buffer); // Dangerous! Possible buffer overflow
// Formatted input
scanf("%s", buffer); // Read a word (stops at space)
scanf("%99s", buffer); // Limit length
scanf("%[^
]", buffer); // Read until newline character
5.2 C++ Style Input Functions
string str;
// Read a word (stops at space)
cin >> str;
// Read a whole line (recommended)
getline(cin, str); // Read a line, discard newline character
getline(cin, str, ';'); // Read until semicolon
// Character array version
char buffer[100];
cin.getline(buffer, 100); // Read a line into character array
5.3 Input Function Comparison Guide
| Scenario | Recommended Function | Reason |
|---|---|---|
| Read a single word | <span>cin >> str</span> |
Simple and direct |
| Read a whole line of text | <span>getline(cin, str)</span> |
Safe, automatic memory management |
| Need to limit length | <span>cin.getline(buffer, size)</span> |
Prevents overflow |
| Read until a specific delimiter | <span>getline(cin, str, delim)</span> |
Flexible parsing |
🔄 Type Conversion and Interoperability
6.1 Mutual Conversion
// Character array → String
char cstr[] = "Hello";
string str = string(cstr);
// String → Character array
const char* ptr = str.c_str();
// Get character array length
int len = strlen(cstr); // Must end with '\0'
💡 Practical Tips and Best Practices
7.1 Safety First
// Incorrect example
char name[10];
strcpy(name, "This is a very long string"); // Buffer overflow!
// Correct approach
string name;
name = "This is a very long string"; // Automatically handles memory
7.2 Performance Optimization
// Multiple concatenation optimization
string result;
result.reserve(1000); // Preallocate space
for (int i = 0; i < 100; i++) {
result += "data";
}
// Avoid unnecessary copies
const string& getData() { // Return reference to avoid copy
static string data = "large data";
return data;
}
7.3 Practical Code Patterns
String Splitting
vector<string> split(const string& str, char delimiter) {
vector<string> tokens;
string token;
istringstream tokenStream(str);
while (getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
Trimming Whitespace
string trim(const string& str) {
size_t start = str.find_first_not_of(" \t\n\r");
size_t end = str.find_last_not_of(" \t\n\r");
return (start == string::npos) ? "" : str.substr(start, end - start + 1);
}
Case-Insensitive Comparison
bool caseInsensitiveCompare(const string& a, const string& b) {
return equal(a.begin(), a.end(), b.begin(), b.end(),
[](char a, char b) { return tolower(a) == tolower(b); });
}
🤔 Selection Guide: When to Use Which Method
8.1 Recommended Use Cases for String Class
✅ Most application scenarios✅ Frequent string modifications✅ Uncertain string length✅ High safety requirements
8.2 Situations Where Character Arrays Can Be Used
✅ Interacting with C language libraries✅ Performance-sensitive scenarios✅ Embedded systems (memory-constrained)✅ Fixed-length short strings
📝 Summary
Through this systematic study, you should have mastered:
- ✅ Characteristics and applicable scenarios of three text data types
- ✅ Correct usage of character handling functions
- ✅ Complete set of C-style string functions
- ✅ Powerful features and convenient operations of C++ string class
- ✅ Safe practices for string input and output
- ✅ Performance optimization and practical programming tips
Remember the core principle: Prioritize using the string class for safety, and use character arrays for performance optimization in specific scenarios.
String manipulation is fundamental in programming, and mastering this knowledge will lay a solid foundation for your C++ programming journey. It is recommended to save this article for reference and continuously practice and apply these techniques in actual programming.
Master strings, master the fundamentals of programming. Feel free to share this article with more learners!
