C++ Strings

🧡 C++ Strings

C++ mein String ka use text (multiple characters) store karne ke liye hota hai.
Modern C++ mein hum zyada tar string class (STL) ka use karte hain, jo safe aur easy hoti hai.


Β 1. string Declare & Initialize

#include <iostream>
#include <string>
using namespace std;
int main() {
string name = “Sanjit”;
cout << name;
return 0;
}


πŸ”Ή 2. String Input (Single Word)

string city;
cin >> city;

⚠️ cin space ke baad input nahi leta
Input: New Delhi
Output: New


πŸ”Ή 3. Full Line Input (getline)

string fullName;
getline(cin, fullName);

βœ” Space ke saath complete line read karta hai


πŸ”Ή 4. cin + getline Problem & Fix

int age;
string name;
cin >> age;
getline(cin, name); // ❌ skip ho jayega

βœ” Correct:

cin >> age;
cin.ignore();
getline(cin, name);

πŸ”Ή 5. String Length

string text = "Hello";
cout << text.length(); // 5

Ya:

cout << text.size();

πŸ”Ή 6. String Concatenation (Join Strings)

string a = "Hello";
string b = "World";
string c = a + ” “ + b;
cout << c;

Output:

Hello World

πŸ”Ή 7. Access String Characters

string name = "Ram";
cout << name[0]; // R

πŸ”Ή 8. Modify String Character

name[0] = 'S';
cout << name; // Sam

πŸ”Ή 9. Common String Functions

string s = "Programming";

cout << s.empty(); // 0 (false)
cout << s.find(“gram”); // position
cout << s.substr(0, 7); // Program


πŸ”Ή 10. String Comparison

string a = "abc";
string b = "abc";
if (a == b) {
cout << “Equal”;
}


πŸ”Ή 11. Loop Through String

string s = "C++";

for (char c : s) {
cout << c << ” “;
}


❌ Common Mistakes

string name = 'Ram'; // ❌ wrong

βœ” Correct:

string name = "Ram";

πŸ“Œ Summary

  • string multiple characters store karta hai

  • getline() space handle karta hai

  • length() / size() se length milti hai

  • Easy, safe & powerful compared to char arrays

You may also like...