ποΈ 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); // 6Loop 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"Replace and Search
const original = "I like cats";
const updated = original.replace("cats", "dogs");
console.log(updated); // "I like dogs"
console.log(original.includes("cats")); // trueSplit 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