std::string

最後更新


提供可成長、擁有所有權的 UTF-8 字串型別 String,以及把任何值轉成字串的 ToString 特徵。

這個模組做什麼


寫程式時,字串有兩種常見來源:寫死在程式裡的文字,和執行時才組出來的文字(使用者輸入、檔案內容、拼接結果)。Rust 用兩個型別分開處理:
型別是什麼能不能改典型用途
&str字串切片(string slice),借用一段 UTF-8 文字不能函式參數、字面值 "hello"
String擁有所有權(ownership)的字串,資料放在堆積(heap)可以需要組合、修改、回傳或長期保存的文字

可以把 String 想成一本自己的筆記本,可以隨意寫、擦、加頁;&str 則像借來看的一頁影本,只能讀。&str 的方法請見 std::str。

匯入


String 與 ToString 都在 prelude(見 std::prelude)中,不需要 use。完整路徑:
  1. use std::string::String;
  2. use std::string::ToString;

常用 API


建立 String:new、from、to_string


最常見的三種建立方式:String::new() 建立空字串;String::from("...") 與 "...".to_string() 從 &str 複製一份成為自己的 String。三者結果相同,挑順手的即可。
簽名:
  1. pub const fn new() -> String
  2. impl From<&str> for String
  3. fn to_string(&self) -> String

範例:
  1. fn main() {
  2. let empty = String::new();
  3. let a = String::from("早安");
  4. let b = "午安".to_string();
  5. let c: String = "晚安".into();
  6. println!("[{}] {} {} {}", empty, a, b, c);
  7. println!("empty 是否為空:{}", empty.is_empty());
  8. }

輸出:
  1. [] 早安 午安 晚安
  2. empty 是否為空:true

push_str 與 push:在尾端加內容


push_str 把一段 &str 接到尾端,push 一次加一個 char。兩者都會修改原字串,所以變數要宣告成 mut。
簽名:
  1. pub fn push_str(&mut self, string: &str)
  2. pub fn push(&mut self, ch: char)

範例:
  1. fn main() {
  2. let mut s = String::from("Rust");
  3. s.push_str(" 很");
  4. s.push('好');
  5. s.push('!');
  6. println!("{}", s);
  7. }

輸出:
  1. Rust 很好!

串接:+ 運算子與 format!


+ 會「拿走」左邊的 String 並把右邊的 &str 接上去,所以左邊的變數之後不能再用。要組合多個片段、或不想交出所有權時,用 format! 最直觀,它回傳全新的 String,所有參數都只是借用。格式語法見 std::fmt。
簽名:
  1. impl Add<&str> for String { type Output = String; }
  2. macro_rules! format { ... }

範例:
  1. fn main() {
  2. let first = String::from("Hello");
  3. let second = String::from("World");
  4. let joined = first + ", " + &second;
  5. println!("{}", joined);
  6. let name = "小明";
  7. let age = 20;
  8. let msg = format!("{}今年 {} 歲,名字有 {} 個字", name, age, name.chars().count());
  9. println!("{}", msg);
  10. println!("second 仍可使用:{}", second);
  11. }

輸出:
  1. Hello, World
  2. 小明今年 20 歲,名字有 2 個字
  3. second 仍可使用:World

注意:first + ... 之後 first 已被移動(move),再使用會編譯失敗。

長度與容量:len、capacity、with_capacity


len() 回傳的是「位元組數」而不是字數;中文字在 UTF-8 中通常佔 3 個位元組。capacity() 是目前已配置、不必重新配置就能容納的位元組數。預先知道大概長度時,用 with_capacity 可以減少重新配置記憶體的次數。
簽名:
  1. pub const fn len(&self) -> usize
  2. pub const fn capacity(&self) -> usize
  3. pub fn with_capacity(capacity: usize) -> String

範例:
  1. fn main() {
  2. let s = String::from("abc中文");
  3. println!("len = {}, 字數 = {}", s.len(), s.chars().count());
  4. let mut buf = String::with_capacity(16);
  5. println!("建立後 len = {}, capacity >= 16:{}", buf.len(), buf.capacity() >= 16);
  6. buf.push_str("0123456789");
  7. println!("寫入後 len = {}, capacity >= 16:{}", buf.len(), buf.capacity() >= 16);
  8. }

輸出:
  1. len = 9, 字數 = 5
  2. 建立後 len = 0, capacity >= 16:true
  3. 寫入後 len = 10, capacity >= 16:true

UTF-8 索引限制:不能用 s[0]


String 不支援 s[0] 這種整數索引,因為一個字可能佔多個位元組,取「第 0 個位元組」常常不是一個完整的字。要取字元就用 chars();要切片就用位元組範圍 &s[a..b],而且邊界必須落在字元邊界上。
簽名:
  1. pub const fn is_char_boundary(&self, index: usize) -> bool
  2. pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output>

範例:
  1. fn main() {
  2. let s = String::from("台北101");
  3. println!("第一個字:{:?}", s.chars().next());
  4. println!("前 3 個位元組:{}", &s[0..3]);
  5. println!("位置 1 是字元邊界嗎?{}", s.is_char_boundary(1));
  6. println!("get(0..1):{:?}", s.get(0..1));
  7. println!("get(0..6):{:?}", s.get(0..6));
  8. }

輸出:
  1. 第一個字:Some('台')
  2. 前 3 個位元組:台
  3. 位置 1 是字元邊界嗎?false
  4. get(0..1):None
  5. get(0..6):Some("台北")

注意:&s[0..1] 這種切在字元中間的範圍會 panic;不確定時用 get,切錯會回傳 None。

insert、remove、truncate、clear:修改內容


insert(idx, ch) 在位元組位置插入字元;remove(idx) 移除並回傳該位置的字元;truncate(n) 只保留前 n 個位元組;clear() 清空但保留容量。
簽名:
  1. pub fn insert(&mut self, idx: usize, ch: char)
  2. pub fn remove(&mut self, idx: usize) -> char
  3. pub fn truncate(&mut self, new_len: usize)
  4. pub fn clear(&mut self)

範例:
  1. fn main() {
  2. let mut s = String::from("ac");
  3. s.insert(1, 'b');
  4. println!("insert 後:{}", s);
  5. let removed = s.remove(0);
  6. println!("remove 取出 {:?},剩下 {}", removed, s);
  7. s.push_str("defg");
  8. s.truncate(3);
  9. println!("truncate(3):{}", s);
  10. s.clear();
  11. println!("clear 後是否為空:{}", s.is_empty());
  12. }

輸出:
  1. insert 後:abc
  2. remove 取出 'a',剩下 bc
  3. truncate(3):bcd
  4. clear 後是否為空:true

注意:這幾個方法的位置參數都是位元組索引,若不在字元邊界或超出長度會 panic。

as_str 與 &String 自動轉成 &str


寫函式時參數建議用 &str,這樣 String 與字面值都能傳進來。&String 會透過解參考強制轉型(deref coercion)自動變成 &str;需要明確取得時用 as_str()。
簽名:
  1. pub const fn as_str(&self) -> &str

範例:
  1. fn shout(text: &str) -> String {
  2. text.to_uppercase()
  3. }
  4. fn main() {
  5. let owned = String::from("hello");
  6. println!("{}", shout(&owned));
  7. println!("{}", shout(owned.as_str()));
  8. println!("{}", shout("world"));
  9. }

輸出:
  1. HELLO
  2. HELLO
  3. WORLD

ToString:任何能 Display 的值都能轉字串


只要型別實作了 Display,就自動擁有 to_string()。自訂型別只要實作 fmt::Display,不必另外實作 ToString。
簽名:
  1. pub trait ToString {
  2. fn to_string(&self) -> String;
  3. }
  4. impl<T: fmt::Display + ?Sized> ToString for T

範例:
  1. use std::fmt;
  2. struct Point {
  3. x: i32,
  4. y: i32,
  5. }
  6. impl fmt::Display for Point {
  7. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  8. write!(f, "({}, {})", self.x, self.y)
  9. }
  10. }
  11. fn main() {
  12. let n = 42.to_string();
  13. let f = 3.5_f64.to_string();
  14. let p = Point { x: 1, y: -2 }.to_string();
  15. println!("{} {} {}", n, f, p);
  16. println!("總長度:{}", n.len() + f.len() + p.len());
  17. }

輸出:
  1. 42 3.5 (1, -2)
  2. 總長度:12

from_utf8:從位元組建立 String


收到一串位元組(例如網路或檔案資料)時,String::from_utf8 會檢查是否為合法 UTF-8,合法回傳 Ok(String),否則回傳 Err。若想把不合法的部分換成替代字元 �,用 String::from_utf8_lossy。
簽名:
  1. pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error>
  2. pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str>

範例:
  1. fn main() {
  2. let good = vec![0xe4, 0xbd, 0xa0, 0xe5, 0xa5, 0xbd];
  3. println!("{:?}", String::from_utf8(good));
  4. let bad = vec![b'h', b'i', 0xff];
  5. match String::from_utf8(bad.clone()) {
  6. Ok(s) => println!("成功:{}", s),
  7. Err(e) => println!("失敗:{}", e),
  8. }
  9. println!("lossy:{}", String::from_utf8_lossy(&bad));
  10. }

輸出:
  1. Ok("你好")
  2. 失敗:invalid utf-8 sequence of 1 bytes from index 2
  3. lossy:hi�

重點整理


  • String 擁有資料、可修改;&str 是借用、唯讀;函式參數優先用 &str
  • 組合多段文字用 format!,+ 會移動左邊的 String
  • len() 是位元組數,字數要用 chars().count()
  • 不能用整數索引字串;切片邊界必須在字元邊界,否則 panic,不確定時用 get
  • 實作 Display 就自動得到 to_string()