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++
stringclass (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
\0is 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:
The
\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
🔹 Best Practice:
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
Conclusion
- C-style strings are character arrays with
\0termination. - C++
stringclass is modern and easy to use. getline()handles multi-word input.- String operations include concatenation, length, access, and modification.