Introduction
In C++, a string is a sequence of characters used to store and manipulate text. Strings are widely used in real-life applications, such as handling names, addresses, messages, and file operations. C++ provides two ways to handle strings:- C-style strings (character arrays)
- C++
string
class (from<string>
library)
C-Style Strings (Character Arrays)
C-style strings are character arrays ending with a null character (\0
).
Example:
Explanation:
char name[] = "John";
initializes a character array.- The null character
\0
is automatically added at the end.
Real-Life Analogy:
Think of a C-style string as a row of lockers where each locker stores a character:J | o | h | n | \0 |
---|
\0
tells C++ where the string ends.
Limitation of C-Style Strings:
- Fixed size (cannot grow dynamically).
- Difficult to manipulate (no built-in functions for concatenation, searching, etc.).
C++ string
Class (Modern Approach)
C++ provides the string
class from the <string>
library, which is more flexible and powerful.
Example:
Explanation:
string name;
declares a string variable.cin >> name;
takes input (but stops at space).cout << name;
prints the string.
Real-Life Analogy:
Imaginestring
as a dynamic notebook where you can write, erase, and modify text freely.
Key Differences
Feature | C-Style Strings (char[] ) | std::string (C++ Strings) |
---|---|---|
Null-Termination | Yes (\0 is required) | No (\0 is managed internally) |
Memory Management | Manual (fixed size) | Dynamic (auto-resizes) |
Safer? | ❌ Prone to buffer overflows | ✅ Safer and more convenient |
Functionality | Limited (needs <cstring> ) | Rich methods (length, find, substr, etc.) |
Always prefer
std::string
over C-style strings unless you have a specific reason to use character arrays (e.g., low-level memory manipulation, embedded systems).
Taking Full-Line Input (getline
)
To handle multi-word input, use getline()
.
Example:
Why getline()
?
cin
only takes a single word, but getline(cin, variable);
reads the whole line, including spaces.
String Operations
Concatenation (Joining Strings)
Explanation:
+
operator joins strings." "
adds a space between first and last names.
Finding String Length
Accessing Characters
Modifying Strings
Common Errors and Solutions
Error | Cause | Solution |
---|---|---|
cin skips input | getline() follows cin | Use cin.ignore() before getline() |
String out of bounds | Accessing invalid index | Ensure index is within 0 to str.length()-1 |
Concatenation error | Using + with char[] | Use string class instead of char[] |
Conclusion
- C-style strings are character arrays with
\0
termination. - C++
string
class is modern and easy to use. getline()
handles multi-word input.- String operations include concatenation, length, access, and modification.