CPP String Data Type
💻 CPP String Data Type – Complete Beginner to Interview Guide
In CPP String Data Type is used to store a sequence of characters (text) such as names, sentences, or messages.
1️⃣ What is String in C++? ⭐
A string is a collection of characters enclosed in double quotes " ".
📌 C++ provides strings using the Standard Template Library (STL).
2️⃣ Header File for String ⭐
📌 Must be included to use string.
3️⃣ Declaring a String Variable ⭐
Syntax
Example
4️⃣ String Example Program ⭐
Output
5️⃣ String Input Using cin ⭐
📌 Reads only one word.
6️⃣ String Input Using getline() ⭐⭐
📌 Reads full line including spaces.
7️⃣ cin + getline() Issue ⚠️
✔ Correct way:
8️⃣ String Length ⭐⭐
Output
📌 .length() or .size() both work.
9️⃣ String Concatenation ⭐⭐
Output
🔟 Accessing Characters in String ⭐⭐
Output
1️⃣1️⃣ Modifying String ⭐⭐
Output
1️⃣2️⃣ String vs Character Array ⭐⭐⭐
| String | Character Array |
|---|---|
| Dynamic size | Fixed size |
| Easy to use | Complex |
| STL support | Manual handling |
1️⃣3️⃣ Common String Errors ❌
❌ Forgetting <string> header
❌ Using cin for multi-word input
❌ Confusing ' ' and " "
❌ Index out of range
📌 Interview Questions (C++ String)
Q1. Difference between cin and getline()?
👉 cin reads one word, getline() reads full line
Q2. How to find length of string?
👉 .length() or .size()
Q3. Is string mutable in C++?
👉 Yes
✅ Summary
✔ string stores text
✔ Uses double quotes
✔ Supports many built-in functions
✔ getline() for full input
✔ Very important for exams & interviews
