Rust(10) - str, String
Rust 中字串分成靜態的 str 跟動態的 String,String 是由 Vec<u8> 組成所以可以增減。
1. 字串串接:
字串串接只能透過 String 進行,靜態的 str 無法被改變。
被串接的對象是一個 &str,串接後回傳一個 String。
fn main() {
let a: &str = "你好";
let b: &str = "世界";
let c: String = String::from(a) + b;
println!("{}", c);
}
串接時 + 號等同於呼叫 String.add,下面是 String.add 的簽名。
#[inline]
fn add(mut self, other: &str) -> String {
self.push_str(other);
self
}
2. 遍歷 String:
str 和 String 都可以透過 chars 進行遍歷。
let s1 = "你好世界";
for ch in s1.chars() {
println!("{}", ch);
}
let s2 = String::from("你好世界");
for ch in s2.chars() {
println!("{}", ch);
}
3. String 的切片:
Rust 使用 Vec<u8> 儲存資料所以拿不滿一個字的時候會出錯。
下面"你"在 utf-8 中佔 3 bytes,所以切片不能只切第一個 byte。
let s = String::from("你好世界");
let ch = &s[0..1]; // 錯誤
println!("{}", ch);
一次拿 3 bytes 可以得到"你"這個字。
let s = String::from("你好世界");
let ch = &s[0..3];
println!("{}", ch);
4. 字串長度:
因為 String 是 Vec<u8> 所以呼叫 len 的時候會回傳 u8 的個數,即字串佔用多少 byte。
fn main() {
let s = String::from("你好世界");
println!("len: {}", s.len()); // 四個中文一共 12 bytes
}
可以先取得每個字再計算字的個數。
fn main() {
let s = String::from("你好世界");
println!("count: {}", s.chars().count());
}
留言
張貼留言