C++ Access Strings

๐Ÿ”Ž C++ Access Strings (Characters Access Karna)

C++ mein string ke individual characters ko access (read / modify) karna bahut common haiโ€”loops, validation, parsing, etc. ke liye.


๐Ÿ”น 1. Indexing Using [] Operator

#include <iostream>
#include <string>
using namespace std;

int main() {
string name = "Sanjit";
cout << name[0]; // S
return 0;
}

๐Ÿ‘‰ Index 0 se start hota hai

Index Character
0 S
1 a
2 n
3 j
4 i
5 t

๐Ÿ”น 2. Access Last Character

string s = "C++";
cout << s[s.length() - 1];

Output:

+

๐Ÿ”น 3. Using at() Function (Safe Method)

string s = "Hello";
cout << s.at(1); // e

โœ” Bounds check karta hai
โŒ Out of range par exception throw karta hai


๐Ÿ”น 4. Modify String Characters

string name = "Ram";
name[0] = 'S';
cout << name;

Output:

Sam

๐Ÿ”น 5. Loop Through String (Using Index)

string s = "Code";

for (int i = 0; i < s.length(); i++) {
cout << s[i] << " ";
}

Output:

C o d e

๐Ÿ”น 6. Range-Based For Loop (Modern C++)

string s = "C++";

for (char ch : s) {
cout << ch << " ";
}


๐Ÿ”น 7. Read-Only Access with const

const string s = "Hello";
cout << s[0]; // โœ” allowed
// s[0] = 'A'; // โŒ not allowed

โŒ Common Mistakes

cout << s[10]; // โŒ Out of range (undefined behavior)

โœ” Safe option:

cout << s.at(10); // throws error (safe)

๐Ÿ“Œ Summary

  • [] โ†’ Fast, no bounds check

  • at() โ†’ Safe, bounds check

  • Indexing starts from 0

  • Characters can be read & modified

  • Looping strings is very common

You may also like...