Day 6:字串操作(進階)
學習目標
- 用切片 / 迭代 / 分割處理字串
- 用 replace / split / trim
- 安全地切片(避免切在字元中間)
今日重點
迭代字元與位元組
for c in "नमस्ते".chars() { // 字元迭代(Unicode 安全)
println!("{}", c);
}
for b in "hello".bytes() { // 位元組迭代
println!("{}", b);
}
分割 / 組合
let csv = "apple,banana,cherry";
let fruits: Vec<&str> = csv.split(',').collect();
println!("{:?}", fruits); // ["apple","banana","cherry"]
let joined = fruits.join(" | ");
println!("{}", joined); // "apple | banana | cherry"
替換 / 去除空白
let s = "Hello, World!";
let new_s = s.replace("World", "Rust"); // "Hello, Rust!"
let padded = " hi ";
println!("{}", padded.trim()); // "hi"
安全切片(重要!)
直接
&s[0..2]若切在字元中間會 panic。用chars().take()較安全。let s = "héllo"; // let sub = &s[0..2]; // 可能 panic(é 是 2 bytes) let first_two: String = s.chars().take(2).collect(); // 安全
練習
fn main() {
let text = "Rust is great, and Rust is fast";
// 1. 計算 "Rust" 出現次數
let count = text.matches("Rust").count();
println!("{}", count);
// 2. 用 split_whitespace 收集單字,倒序成新 String
let words: Vec<&str> = text.split_whitespace().collect();
let rev = words.iter().rev().cloned().collect::<Vec<_>>().join(" ");
println!("{}", rev);
// 3. 把 "Rust" 全換成 "⚙️Rust"
}
自我檢查
- 會用 chars() 與 bytes() 迭代
- 會用 split / join / replace / trim
- 知道直接 &s[a..b] 可能切斷 Unicode 而 panic
- 用 chars().take() 做安全取前 N 字
深入連結
- The Book 第 8 章「Methods for Iterating Over Strings」