C++ String Concatenation
💻 C++ String Concatenation
String concatenation in C++ means joining two or more strings to form a single string.
C++ provides multiple safe and easy ways to do this.
1️⃣ Using + Operator ⭐ (Most Common)
Example
Output
📌 Works only with string type, not char.
2️⃣ Using append() Function ⭐⭐
Example
Output
📌 Modifies the original string (s1).
3️⃣ Concatenating String with Variables ⭐⭐
Output
📌 Use to_string() to convert numbers into string.
4️⃣ Concatenating Multiple Strings ⭐⭐
Output
5️⃣ Using += Operator ⭐⭐
Output
📌 Efficient and clean for step-by-step joining.
6️⃣ Concatenating User Input Strings ⭐⭐
Input
Output
7️⃣ ❌ Invalid String Concatenation (Common Mistake)
✔ Correct way:
8️⃣ string vs char Concatenation ⚠️
✔ Correct:
Output
📌 Interview Questions (String Concatenation)
Q1. Which operator is used for string concatenation?
👉 +
Q2. Can we concatenate string with integer directly?
👉 No (use to_string())
Q3. Difference between + and append()?
👉 + creates new string, append() modifies existing one
✅ Summary
✔ Use + for simple concatenation
✔ Use append() for modifying strings
✔ Use += for efficiency
✔ Convert numbers using to_string()
✔ Avoid mixing char and string directly
