Day 5:字串操作(基礎)
學習目標
- 建立、修改、拼接 String
- 理解 push_str / push / format!
- 讀懂字串的編碼特性
今日重點
建立與修改
let mut s = String::from("Hello");
s.push_str(", world!"); // 追加字串
s.push('!'); // 追加單一字元
println!("{}", s); // "Hello, world!!"
let empty = String::new();
let from_literal = "hi".to_string();
拼接
// format!(最推薦,不吞所有權)
let name = "Alice";
let age = 30;
let greeting = format!("Hello, {}! You are {} years old.", name, age);
// 用 +(需注意 move)
let s1 = String::from("Hello ");
let s2 = String::from("World");
let s3 = s1 + &s2; // s1 被 move,&s2 借用
// s1 之後無效
Rust 字串是 UTF-8
String::len() 回傳**位元組數**,不是字元數。中文、emoji 是多方元組。
let s = "你好";
println!("{}", s.len()); // 6(3 個中文字 × 2 bytes ?不,UTF-8 中文字是 3 bytes)→ 6
println!("{}", s.chars().count()); // 2(字元數)
練習
let mut words = String::from("first");
words.push(' ');
words.push_str("second");
words.push(' ');
words.push_str("third");
println!("{}", words); // "first second third"
// 1. 用 format! 組合 "今天天氣很好"
// 2. 印出 "abc" 的 len 與 chars().count()
// 3. 想想為什麼 len 和 chars().count() 對多國字不同
自我檢查
深入連結
- The Book 第 8 章「Storing UTF-8 Encoded Text with Strings」