CPP String Data Type

C++ Tutorial

💻 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 " ".

string name = "Sanjit";

📌 C++ provides strings using the Standard Template Library (STL).


2️⃣ Header File for String ⭐

#include <string>

📌 Must be included to use string.


3️⃣ Declaring a String Variable ⭐

Syntax

string variable_name;

Example

string city = "Kolkata";

4️⃣ String Example Program ⭐


 

Output

Sanjit

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

5

📌 .length() or .size() both work.


9️⃣ String Concatenation ⭐⭐


 

Output

Hello World

🔟 Accessing Characters in String ⭐⭐


 

Output

C

1️⃣1️⃣ Modifying String ⭐⭐


 

Output

Yello

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

You may also like...