πŸ—“οΈ Day 41 Bonus: Strings – Manipulation and Character Operations

🧠 Concept Deep Dive

Strings are sequences of characters and are widely used to represent text. They are immutable in most languages, including TypeScript.

What is a String?

  • A string is a sequence of characters, such as letters, numbers, or symbols.
  • Strings are immutable, meaning once created, their content can't be changed.
  • Common operations include slicing, searching, replacing, and concatenating.

πŸ” Core Concepts

Creating Strings

const greeting = "Hello, world!";
const name = 'Alice';

Access Characters by Index

const word = "hello";
console.log(word[0]); // 'h'
console.log(word[4]); // 'o'

String Length

console.log("banana".length); // 6

Loop Through a String

const s = "cat";
for (let i = 0; i < s.length; i++) {
  console.log(s[i]);
}

for (const char of s) {
  console.log(char);
}

Concatenation

const first = "Good";
const second = "Morning";
console.log(first + " " + second); // "Good Morning"

Substring and Slice

const text = "abcdefg";
console.log(text.slice(1, 4)); // "bcd"
const original = "I like cats";
const updated = original.replace("cats", "dogs");
console.log(updated); // "I like dogs"

console.log(original.includes("cats")); // true

Split and Join

const sentence = "this is fun";
const words = sentence.split(" ");
console.log(words); // ["this", "is", "fun"]

const joined = words.join("-");
console.log(joined); // "this-is-fun"

🎨 ASCII Visualization

String: "hello"
Index:   0   1   2   3   4
         ↓   ↓   ↓   ↓   ↓
        'h' 'e' 'l' 'l' 'o'

πŸ‹οΈ Homework (LeetCode-style)

Problem 1: First Character

function firstChar(s: string): string {
  return s[0];
}

Input: "hello" β†’ Output: "h"

Problem 2: Count Characters

function charCount(s: string): number {
  return s.length;
}

Input: "banana" β†’ Output: 6

Problem 3: Reverse String

function reverseString(s: string): string {
  return s.split('').reverse().join('');
}

Input: "abc" β†’ Output: "cba"

Problem 4: Replace Word

function replaceWord(s: string, from: string, to: string): string {
  return s.replace(from, to);
}

Input: ("I like cats", "cats", "dogs") β†’ Output: "I like dogs"

Problem 5: Check Palindrome

function isPalindrome(s: string): boolean {
  const clean = s.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
  return clean === clean.split('').reverse().join('');
}

Input: "racecar" β†’ Output: true


πŸ“œ Summary

  • Strings are sequences of characters and are immutable.
  • You can access characters by index and use many built-in methods.
  • Common operations include slicing, joining, splitting, and replacing.

πŸ’– Coming Up

Day 5: Objects and Maps – Key-Value Data Structures

This page was last edited on 2025-08-01 11:49

Powered by Wiki|Docs

This page was last edited on 2025-08-01 11:49

Tri Nguyen
No Copyright

Powered by Wiki|Docs