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。完整路徑:- use std::string::String;
- use std::string::ToString;
常用 API
建立 String:new、from、to_string
最常見的三種建立方式:
String::new() 建立空字串;String::from("...") 與 "...".to_string() 從 &str 複製一份成為自己的 String。三者結果相同,挑順手的即可。簽名:
- pub const fn new() -> String
- impl From<&str> for String
- fn to_string(&self) -> String
範例:
- fn main() {
- let empty = String::new();
- let a = String::from("早安");
- let b = "午安".to_string();
- let c: String = "晚安".into();
- println!("[{}] {} {} {}", empty, a, b, c);
- println!("empty 是否為空:{}", empty.is_empty());
- }
輸出:
- [] 早安 午安 晚安
- empty 是否為空:true
push_str 與 push:在尾端加內容
push_str 把一段 &str 接到尾端,push 一次加一個 char。兩者都會修改原字串,所以變數要宣告成 mut。簽名:
- pub fn push_str(&mut self, string: &str)
- pub fn push(&mut self, ch: char)
範例:
- fn main() {
- let mut s = String::from("Rust");
- s.push_str(" 很");
- s.push('好');
- s.push('!');
- println!("{}", s);
- }
輸出:
- Rust 很好!
串接:+ 運算子與 format!
+ 會「拿走」左邊的 String 並把右邊的 &str 接上去,所以左邊的變數之後不能再用。要組合多個片段、或不想交出所有權時,用 format! 最直觀,它回傳全新的 String,所有參數都只是借用。格式語法見 std::fmt。簽名:
- impl Add<&str> for String { type Output = String; }
- macro_rules! format { ... }
範例:
- fn main() {
- let first = String::from("Hello");
- let second = String::from("World");
- let joined = first + ", " + &second;
- println!("{}", joined);
- let name = "小明";
- let age = 20;
- let msg = format!("{}今年 {} 歲,名字有 {} 個字", name, age, name.chars().count());
- println!("{}", msg);
- println!("second 仍可使用:{}", second);
- }
輸出:
- Hello, World
- 小明今年 20 歲,名字有 2 個字
- second 仍可使用:World
注意:
first + ... 之後 first 已被移動(move),再使用會編譯失敗。長度與容量:len、capacity、with_capacity
len() 回傳的是「位元組數」而不是字數;中文字在 UTF-8 中通常佔 3 個位元組。capacity() 是目前已配置、不必重新配置就能容納的位元組數。預先知道大概長度時,用 with_capacity 可以減少重新配置記憶體的次數。簽名:
- pub const fn len(&self) -> usize
- pub const fn capacity(&self) -> usize
- pub fn with_capacity(capacity: usize) -> String
範例:
- fn main() {
- let s = String::from("abc中文");
- println!("len = {}, 字數 = {}", s.len(), s.chars().count());
- let mut buf = String::with_capacity(16);
- println!("建立後 len = {}, capacity >= 16:{}", buf.len(), buf.capacity() >= 16);
- buf.push_str("0123456789");
- println!("寫入後 len = {}, capacity >= 16:{}", buf.len(), buf.capacity() >= 16);
- }
輸出:
- len = 9, 字數 = 5
- 建立後 len = 0, capacity >= 16:true
- 寫入後 len = 10, capacity >= 16:true
UTF-8 索引限制:不能用 s[0]
String 不支援 s[0] 這種整數索引,因為一個字可能佔多個位元組,取「第 0 個位元組」常常不是一個完整的字。要取字元就用 chars();要切片就用位元組範圍 &s[a..b],而且邊界必須落在字元邊界上。簽名:
- pub const fn is_char_boundary(&self, index: usize) -> bool
- pub fn get<I: SliceIndex<str>>(&self, i: I) -> Option<&I::Output>
範例:
- fn main() {
- let s = String::from("台北101");
- println!("第一個字:{:?}", s.chars().next());
- println!("前 3 個位元組:{}", &s[0..3]);
- println!("位置 1 是字元邊界嗎?{}", s.is_char_boundary(1));
- println!("get(0..1):{:?}", s.get(0..1));
- println!("get(0..6):{:?}", s.get(0..6));
- }
輸出:
- 第一個字:Some('台')
- 前 3 個位元組:台
- 位置 1 是字元邊界嗎?false
- get(0..1):None
- get(0..6):Some("台北")
注意:
&s[0..1] 這種切在字元中間的範圍會 panic;不確定時用 get,切錯會回傳 None。insert、remove、truncate、clear:修改內容
insert(idx, ch) 在位元組位置插入字元;remove(idx) 移除並回傳該位置的字元;truncate(n) 只保留前 n 個位元組;clear() 清空但保留容量。簽名:
- pub fn insert(&mut self, idx: usize, ch: char)
- pub fn remove(&mut self, idx: usize) -> char
- pub fn truncate(&mut self, new_len: usize)
- pub fn clear(&mut self)
範例:
- fn main() {
- let mut s = String::from("ac");
- s.insert(1, 'b');
- println!("insert 後:{}", s);
- let removed = s.remove(0);
- println!("remove 取出 {:?},剩下 {}", removed, s);
- s.push_str("defg");
- s.truncate(3);
- println!("truncate(3):{}", s);
- s.clear();
- println!("clear 後是否為空:{}", s.is_empty());
- }
輸出:
- insert 後:abc
- remove 取出 'a',剩下 bc
- truncate(3):bcd
- clear 後是否為空:true
注意:這幾個方法的位置參數都是位元組索引,若不在字元邊界或超出長度會 panic。
as_str 與 &String 自動轉成 &str
寫函式時參數建議用
&str,這樣 String 與字面值都能傳進來。&String 會透過解參考強制轉型(deref coercion)自動變成 &str;需要明確取得時用 as_str()。簽名:
- pub const fn as_str(&self) -> &str
範例:
- fn shout(text: &str) -> String {
- text.to_uppercase()
- }
- fn main() {
- let owned = String::from("hello");
- println!("{}", shout(&owned));
- println!("{}", shout(owned.as_str()));
- println!("{}", shout("world"));
- }
輸出:
- HELLO
- HELLO
- WORLD
ToString:任何能 Display 的值都能轉字串
只要型別實作了
Display,就自動擁有 to_string()。自訂型別只要實作 fmt::Display,不必另外實作 ToString。簽名:
- pub trait ToString {
- fn to_string(&self) -> String;
- }
- impl<T: fmt::Display + ?Sized> ToString for T
範例:
- use std::fmt;
- struct Point {
- x: i32,
- y: i32,
- }
- impl fmt::Display for Point {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "({}, {})", self.x, self.y)
- }
- }
- fn main() {
- let n = 42.to_string();
- let f = 3.5_f64.to_string();
- let p = Point { x: 1, y: -2 }.to_string();
- println!("{} {} {}", n, f, p);
- println!("總長度:{}", n.len() + f.len() + p.len());
- }
輸出:
- 42 3.5 (1, -2)
- 總長度:12
from_utf8:從位元組建立 String
收到一串位元組(例如網路或檔案資料)時,
String::from_utf8 會檢查是否為合法 UTF-8,合法回傳 Ok(String),否則回傳 Err。若想把不合法的部分換成替代字元 �,用 String::from_utf8_lossy。簽名:
- pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error>
- pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str>
範例:
- fn main() {
- let good = vec![0xe4, 0xbd, 0xa0, 0xe5, 0xa5, 0xbd];
- println!("{:?}", String::from_utf8(good));
- let bad = vec![b'h', b'i', 0xff];
- match String::from_utf8(bad.clone()) {
- Ok(s) => println!("成功:{}", s),
- Err(e) => println!("失敗:{}", e),
- }
- println!("lossy:{}", String::from_utf8_lossy(&bad));
- }
輸出:
- Ok("你好")
- 失敗:invalid utf-8 sequence of 1 bytes from index 2
- lossy:hi�
重點整理
String擁有資料、可修改;&str是借用、唯讀;函式參數優先用&str- 組合多段文字用
format!,+會移動左邊的String len()是位元組數,字數要用chars().count()- 不能用整數索引字串;切片邊界必須在字元邊界,否則 panic,不確定時用
get - 實作
Display就自動得到to_string()