Foundations

These are must-know before solving problems.

πŸ“˜ 1. Mutable vs Immutable Strings

In C++:

βœ… std::string is mutable

You can change characters in place.

string s = "hello";
s[0] = 'H';   // modifies original string

After modification β†’ "Hello"

❌ Character arrays are also mutable (as long as not stored in read-only memory)

char arr[] = "hello";
arr[1] = 'a'; // works

BUT this is NOT allowed:

char* s = "hello";  
s[1] = 'a';   // ❌ undefined behavior (string literal is read-only)

πŸ“Œ Takeaway

Type Mutable? Notes
std::string βœ… Yes Safe, dynamic size
char arr[] βœ“ Yes Static size
char* s = "literal" ❌ No Read-only memory

πŸ“˜ 2. Character Arrays vs std::string

πŸ”· Character Array (char[])

char name[10] = "Ajay";

If you modify without checking size β†’ risk of overflow.

string name = "Ajay";
name += " Gupta";

Differences in memory view:

Char array:

'A' 'j' 'a' 'y' '\0'

std::string internals:

size, capacity, pointer β†’ ['A','j','a','y']

πŸ“Œ Conclusion:

Use std::string unless you specifically need low-level C-style operations.

πŸ“˜ 3. Common String Operations

Let’s see the most used methods in DSA.

πŸ”Ή Length

string s = "hello";
int len = s.length();  // or s.size()

πŸ”Ή Substring

string s = "abcdef";
string sub = s.substr(1, 3);  
// starts at index 1, length 3 β†’ "bcd"

πŸ”Ή Concatenation

string a = "Ajay";
string b = "Gupta";
string c = a + " " + b;

πŸ”Ή Comparison

Lexicographical comparison (dictionary order):

string a = "apple";
string b = "banana";
if (a < b) cout << "apple comes first";

Character comparison uses ASCII values.

πŸ”Ή Search operations

string s = "hello world";
int pos = s.find("world");   // returns 6

If not found β†’ returns string::npos.

πŸ”Ή Access characters

char ch = s[2];
s[3] = 'x';

πŸ“Œ std::to_string() β€” Overview

Converts numeric values to std::string

πŸ“˜ Example: Convert int to string

int x = 42;
string s = to_string(x);  
cout << s;   // "42"

πŸ“˜ Example: Using inside concatenation

int age = 25;
string info = "Age = " + to_string(age);
cout << info;

⚠️ Precision Issue (Important!)

to_string(double) always prints 6 decimal places.

to_string(3.1) β†’ "3.100000"

If you want precise formatting, use:

#include <sstream>

stringstream ss;
ss << fixed << setprecision(2) << 3.14159;
string s = ss.str();    // "3.14"

βœ… stringstream

Example:

stringstream ss;
ss << "Value = " << 42;
string s = ss.str();

βœ” Use stringstream when:

πŸ“˜ 4. ASCII & Unicode Basics

πŸ”Ή ASCII

char c = 'a';
int val = (int)c;   // 97 (ASCII of 'a')

Character manipulation using ASCII:

char up = c - 32;   // 'a' β†’ 'A'

πŸ”Ή Unicode

Supports all world languages.

C++ uses:

For DSA interviews: πŸ‘‰ ASCII-based problems are 95% of what you need πŸ‘‰ Unicode only matters in advanced parsing tasks