C++ Fundamentals

Lesson 06 · 15 min

string Basics for Interviews

Indexing chars, ascii tricks, two pointers on strings, and anagram counting.

std::string

Strings are like vector<char> with extras.

string s = "code";
char c = s[0];          // 'c'
int n = (int)s.size();
s += 'x';

Lowercase letter index

int idx = s[i] - 'a';  // 0..25 if s[i] is 'a'..'z'

Two pointers palindrome

Skip non-alphanumeric, compare lowercased ends — classic Valid Palindrome.

Anagrams

Count frequency of 26 letters (or map for unicode). Same counts ⇒ anagram.

Substring windows

Sliding window on strings: grow R, shrink L when a constraint breaks (e.g. duplicate char).

Rules to remember

  • s[i] is char; promote carefully in arithmetic.
  • Prefer s.size() over strlen-style C APIs.
  • For ASCII letters, 'a'..'z' → freq[c-'a'].
  • Don't modify string while iterating blindly — know your indices.

Check yourself

1. 'z' - 'a' equals?

Practice what you learned