💬 Strings

Character Operations

Char ↔ int, isDigit, isLetter, alphabet index — used constantly in interviews

Most string problems boil down to treating characters as numbers. The key insight: characters are just integers under the hood — 'a' = 97, '0' = 48. Subtract to get indices.

Language:
Python
Loading...

All languages — Char ↔ number conversions

JavaScript
// JS: charCodeAt / fromCharCode
const c = 'a';
console.log(c.charCodeAt(0));        // 97
console.log(String.fromCharCode(97)); // 'a'

// Alphabet index
console.log('c'.charCodeAt(0) - 'a'.charCodeAt(0)); // 2

// Digit char → int
console.log('7'.charCodeAt(0) - '0'.charCodeAt(0)); // 7
console.log(parseInt('7'));                           // 7

// Frequency array
const freq = new Array(26).fill(0);
for (const ch of "hello") {
  freq[ch.charCodeAt(0) - 97]++;
}
console.log(freq);
TypeScript
const c: string = 'a';
console.log(c.charCodeAt(0));         // 97
console.log(String.fromCharCode(97));  // 'a'

const idx: number = 'c'.charCodeAt(0) - 'a'.charCodeAt(0); // 2

const freq: number[] = new Array(26).fill(0);
for (const ch of "hello") {
  freq[ch.charCodeAt(0) - 97]++;
}
Java
// Java: char is just an int
char c = 'a';
int code = c;               // 97 (implicit cast)
char back = (char) 97;      // 'a'

// Alphabet index (0-based)
int idx = 'c' - 'a';        // 2
char letter = (char)('a' + 2); // 'c'

// Digit char → int (the fast way)
int digit = '7' - '0';     // 7
// NOT: Integer.parseInt(String.valueOf(c)) — overkill

// int → digit char
char dc = (char)('0' + 5); // '5'

// Frequency array for lowercase letters
int[] freq = new int[26];
for (char ch : "hello".toCharArray()) {
    freq[ch - 'a']++;
}
System.out.println(java.util.Arrays.toString(freq));
Go
package main
import "fmt"

func main() {
    // Go: rune is int32
    c := 'a'
    fmt.Println(c)          // 97
    fmt.Println(string(c))  // "a"

    // Alphabet index
    idx := 'c' - 'a'       // 2
    fmt.Println(idx)

    // Digit char → int
    digit := '7' - '0'     // 7
    fmt.Println(digit)

    // Frequency array
    freq := [26]int{}
    for _, ch := range "hello" {
        freq[ch-'a']++
    }
    fmt.Println(freq)
}
C++
#include <iostream>
#include <string>
#include <array>
using namespace std;

int main() {
    char c = 'a';
    int code = c;              // 97
    char back = (char)97;      // 'a'

    // Alphabet index
    int idx = 'c' - 'a';      // 2
    char letter = 'a' + 2;    // 'c'

    // Digit char → int
    int digit = '7' - '0';    // 7

    // Frequency array
    array<int, 26> freq{};
    string s = "hello";
    for (char ch : s) freq[ch - 'a']++;

    for (int f : freq) cout << f << " ";
    cout << endl;
}