星期日, 11月 26, 2023

Rust - String

String

Rust 中 String 的標準類型是 String

編碼是 UTF-8,這個特性給其他語言轉換過來的使用者比較疑惑的性質。

  • 無法使用 [] 取得字元。
  • .len() 取得的是 Bytes 長度,而非字數。
無法使用 [] 取得字元。
let mut st = String::from("您好,Rust");
println!("{}", st[0]);
會得到編譯錯誤
`String` cannot be indexed by `{integer}`
Rust 不支援 [] 的原因
  • Rust 中 String 是以 byte 為單位儲存
  • UTF-8 每個字不定長度
  • 計算字必須由第一個 Bytes 開始解析,時間複雜度為 O(n),而非 O(1)
那如何取得字數與特定位置的字呢?
let hello = "您好";
    
println("The second character is {}", hello.chars().nth(1)); // Get 好
println("The length of string is {}", hello.chars().count()); // Get 2
.chars() 可以取得對應字串的 iterator 來進行 parse 的動作。 但 Rust 不支援 grapheme
let hello = "Z̫̫̳̰̦͙͙̒̇̽̒͗̑̂̋̚ạ͈̳̟̙͉̥̦̙̒̔̃͋̅͛̐l͕̯̟͖̣͊̓̒̂̑̽̊̃͑̃̓̽ḡ̟̲͚̞͆͊̋̏̽̏̉ͅô̤͈̩̖̞̙̲͚͍͓̘͉͂́̆";
    
println("The second character is {}", hello.chars().nth(0)); // Get Z
println("The length of string is {}", hello.chars().count()); // Get 82
Rust 中的 char 為了能夠表示 Unicode 字元。其大小為 4 bytes
let c = '您'; // 
println!("{}", get_type_size(&c)); // get 4
每次 .chars 都會重新 Parse,想要保留結果可以將 String 轉為 Vec
let re = "您好, Rust。這是一個嘗試";
let re_v: Vec<char> = re.chars().collect();
print!("{}{}\n", re_v[0], re_v[1]); // Get 您好

String 與 str

在 Rust 中 Function 常常可以看到以下寫法
fn first_word(s: &str) -> &str {
}
&str
  • 有 & 所以是一個 Reference
  • str 是 String Slice, 相比一般 Reference 多了 "長度" 的資料
以下得範例
let p_i32: i32 = 0;
let p_String: String = format!("Hello world");

let r_i32 = &p_i32;
let r_String = &p_String;
let r_slice = &p_String[..]; // Full Size String Slice
型別 大小
&p_i32 &i32 8
&p_String &String 8
&p_String[..] &str 16
&str 相比 &String 多出的 8 bytes 就是紀錄長度需要的大小。

沒有留言: