C++: C-Style Strings
Last updated: 2026-08-26
C++ has two types of strings:
- C-style strings (character arrays)
- C++ string (covered later)
This lesson covers C-style strings first — they are a legacy from C that C++ maintains for compatibility. Understanding them helps you grasp the underlying principles of strings.
1. What is a C-Style String?
(1) 1.1 Essence: Character Array + Null Terminator
A C-style string is simply a character array, with one special rule:
- The last character must be
\0(null character, ASCII code 0) \0marks the end of the string
"Hello" in memory:
+---+---+---+---+---+----+
| H | e | l | l | o | \0 |
+---+---+---+---+---+----+
0 1 2 3 4 5 ← indices
💡 Key point: The length of a C-style string is 5 (Hello), but the array size must be at least 6 (to store \0).
2. Declaration and Initialization
(1) 2.1 Declaring a C-Style String
Syntax:
char stringName[Size];
Example:
▶ Example 2: Basic Programming Practice (Difficulty ⭐)
#include <iostream>
int main() {
char name[20]; // Can store 19 chars + 1 \0
name[0] = 'H';
name[1] = 'e';
name[2] = 'l';
name[3] = 'l';
name[4] = 'o';
name[5] = '\0'; // Don't forget the null terminator!
std::cout << "Name: " << name << std::endl; // Hello
return 0;
}
Output:
Name: Hello
💡 Tip: Manually adding \0 is tedious — you'll learn simpler methods later.
(2) 2.2 Initializing a C-Style String
Method 1: Initialize with a string literal
#include <iostream>
int main() {
char name = "Hello"; // ✅ Compiler auto-adds \0, array size is 6
std::cout << "Name: " << name << std::endl;
return 0;
}
💡 Key point: When initializing with a string literal, you don't need to specify the array size — the compiler calculates it automatically (including \0).
3. Common String Functions
C-style string functions are in the cstring header file.
(1) 3.1 strlen: Calculate String Length
#include <iostream>
#include <cstring> // Must include this header
int main() {
char name = "Hello";
std::cout << "String: " << name << std::endl;
std::cout << "Length: " << std::strlen(name) << std::endl; // 5(excluding \0)
return 0;
}
💡 Tip: std::strlen returns the number of effective characters (excluding \0), while sizeof returns the array size (including \0).
char name = "Hello";
std::cout << sizeof(name) << std::endl; // 6(Array size)
std::cout << std::strlen(name) << std::endl; // 5(effective character count)
(2) 3.2 strcpy: Copy a String
#include <iostream>
#include <cstring>
int main() {
char src = "Hello";
char dest[20];
std::strcpy(dest, src); // Copy src to dest
std::cout << "src:" << src << std::endl;
std::cout << "dest:" << dest << std::endl;
return 0;
}
⚠️ Warning: std::strcpy does not check the destination array's size — if dest is too small, it will cause a buffer overflow!
Safer function (after C++11):
std::strncpy(dest, src, sizeof(dest) - 1); // Copy at most sizeof(dest)-1 characters
dest[sizeof(dest) - 1] = '\0'; // Manually add null terminator
(3) 3.3 strcat: Concatenate Strings
#include <iostream>
#include <cstring>
int main() {
char greeting[50] = "Hello, ";
char name = "World";
std::strcat(greeting, name); // Append name to greeting
std::cout << greeting << std::endl; // Hello, World
return 0;
}
(4) 3.4 strcmp: Compare Strings
#include <iostream>
#include <cstring>
int main() {
char str1 = "Hello";
char str2 = "Hello";
char str3 = "World";
std::cout << "strcmp(str1, str2) = " << std::strcmp(str1, str2) << std::endl;
std::cout << "strcmp(str1, str3) = " << std::strcmp(str1, str3) << std::endl;
return 0;
}
Return values:
0: the two strings are equal< 0: the first string is less than the second> 0: the first string is greater than the second
💡 Tip: Don't use == to compare C-style strings! == compares addresses, not content.
char str1 = "Hello";
char str2 = "Hello";
if (str1 == str2) { // ❌ Error: Comparing addresses, not content
// ...
}
if (std::strcmp(str1, str2) == 0) { // ✅ Correct:Use strcmp to compare content
// ...
}
4. Handling C-Style Strings with cin and cout
(1) 4.1 Reading Strings
#include <iostream>
int main() {
char name[20];
std::cout << "Please enter your name: ";
std::cin >> name; // ✅ Can read strings (but no spaces)
std::cout << "Hello," << name << "!" << std::endl;
return 0;
}
💡 Problem: cin >> stops at whitespace! If you enter "John Smith", it only reads "John".
Solution: Use std::cin.getline
#include <iostream>
int main() {
char name[50];
std::cout << "Please enter your full name: ";
std::cin.getline(name, 50); // ✅ Read entire line (including spaces)
std::cout << "Hello," << name << "!" << std::endl;
return 0;
}
5. Practice: Simple String Processing
▶ Example 1: Counting Vowels in a String (Difficulty ⭐⭐)
#include <iostream>
#include <cstring>
int main() {
char str[100];
std::cout << "Please enter a string: ";
std::cin.getline(str, 100);
int vowels = 0;
for (int i = 0; i < std::strlen(str); i++) {
char c = str[i];
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
vowels++;
}
}
std::cout << "Vowel count: " << vowels << std::endl;
return 0;
}
Output:
Please enter a string:
Vowel count:
Running result:
Please enter a string: Hello World
Vowel count: 3
6. Common Errors
(1) 6.1 Forgetting to Leave Space for \0
Error example:
#include <iostream>
int main() {
char name[5] = "Hello"; // ❌ Error: "Hello" Need 6 chars (including \0), but array size is only 5
std::cout << name << std::endl;
return 0;
}
Fix:
char name[6] = "Hello"; // ✅ Correct:Array size must be at least 6
(2) 6.2 Using = to Assign a String
Error example:
#include <iostream>
int main() {
char str1[20];
char str2 = "Hello";
str1 = str2; // ❌ Error: Cannot assign to array
str1 = "World"; // ❌ Error: Cannot assign to array
return 0;
}
Fix: Use strcpy
#include <iostream>
#include <cstring>
int main() {
char str1[20];
char str2 = "Hello";
std::strcpy(str1, str2); // ✅ Correct:Use strcpy to copy
std::cout << str1 << std::endl;
return 0;
}
❓ FAQ
Q: When should I use C-style strings, and when should I use C++ strings? A: Prefer C++ strings (covered later), unless: > 1. You're maintaining legacy code (C code) > 2. You're doing very low-level optimization (C-style strings are more efficient)
C++ strings are safer and easier to use; recommended for beginners.
Q: Why does char name = "Hello" work, but int arr = {1, 2, 3} not work? A: Only string literals can directly initialize character arrays.
CPPchar name = "Hello"; // OK int arr = {1, 2, 3}; // OK(this is an initializer list, not a string literal)
Q: How do I convert a C-style string to a C++ string?
A: You can assign directly (the C++ string constructor handles the conversion automatically).
CPP#include `<iostream>` #include `<string>` int main() { char cstr[] = "Hello"; std::string cppStr = cstr; // Automatic conversion std::cout << cppStr << std::endl; return 0; }
▶ Example 3: String Length and Copy (Difficulty ⭐)
#include <iostream>
#include <cstring>
int main() {
char src[] = "Hello";
char dest[20];
std::cout << "src length: " << strlen(src) << std::endl;
strcpy(dest, src);
std::cout << "After copy: " << dest << std::endl;
return 0;
}
Output:
src length: 5
After copy: Hello
strlen() to get the length and strcpy() to copy. Make sure the destination array is large enough!
📖 Summary
- C-style strings are character arrays terminated by
\0 - Common functions:
strlen(length),strcpy(copy),strcat(concatenate),strcmp(compare) - Don't use
==to compare C-style strings — usestrcmp - Don't use
=to assign C-style strings — usestrcpy - C-style strings are unsafe (prone to buffer overflow); prefer C++ strings
📝 Exercises
-
Basic (Difficulty ⭐): Declare a C-style string
char str = "Hello, World!", then output its length and each character. -
Intermediate (Difficulty ⭐⭐): Write a program that lets the user enter two strings and compares whether they are equal (using
strcmp). -
Challenge (Difficulty ⭐⭐⭐): Write a program that implements "string reversal":
-
Let the user enter a string
-
Reverse it (e.g.,
"Hello"becomes"olleH") -
Implement it using C-style strings (no C++ string allowed)
- C-style strings: character arrays terminated by \0
- Common functions: strlen/strcpy/strcat/strcmp
- C strings are initialized with double quotes; char arrays must reserve space for \0
- Drawbacks: unsafe (buffer overflow), cumbersome to manipulate
- Modern C++ recommends using std::string instead of C-style strings
11. 🚀 Next Step
Now that you've learned C-style strings, let's move on to C++ string (Lesson 19) — a safer, easier-to-use string class!