位元詩人 [Rust] 程式設計教學:字串 (String)

Facebook Twitter LinkedIn LINE Skype EverNote GMail Yahoo Email

Rust 字串

Rust 的字串有以下兩種:

  • String 類別是以 UTF8 編碼、可伸縮的字串
  • str 是基礎型別,通常是使用 &str,即指向 str 的參考

另外,Rust 還有字元 (char) 型別,同樣也是以 UTF8 編碼。

建立字串常數時,預設型別是 &str,即指向 str 的參考,但是,若想要使用 String 類別的方法時,可以轉為 String 物件。

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. fn main() {
  2.    // Reference to str
  3.    let s: &str = "Hello";
  4.  
  5.    // String object
  6.    let s_obj: String = String::from("Hello");
  7. }

對字串進行索引

由於 Rust 字串為 UTF8 字串,其內部長度和字元數不同,不能直接對其進行索引。以下的範例是錯誤的:

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. fn main() {
  2. assert_eq!("Hello"[0], "H");
  3. }

本例引發以下錯誤訊息:

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. error[E0277]: the trait bound `std::string::String: std::ops::Index<{integer}>` is not satisfied

如果想要得到單一的字元,需用 chars 方法,會得到走訪字元的迭代器。

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. fn main() {
  2. assert_eq!("你好,麥可".chars().nth(1).unwrap(), '好');
  3. }

字串相接

字串間可以用 +相接,相接的方式是以 String 物件接 &str,如下:

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. fn main() {
  2.     assert_eq!("Hello ".to_string() + "World", "Hello World");
  3. }

如果要將兩個 String 物件相接,則要將 String 物件取參考,轉為 &str,如下:

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. fn main() {
  2.     let s1 = String::from("Hello ");
  3.     let s2 = String::from("World");
  4.  
  5.     assert_eq!(s1 + &s2, "Hello World");
  6. }

格式化字串

Rust 提供數個格式化字串的巨集,包括:

  • format!:將格式化字串轉為 String 物件
  • println!:將格式化字串印到終端機,附帶換行字元
  • print!:將格式化字串印到終端機,但不附加換行字元
  • writeln!:將格式化字串寫入特定的 buffer 物件,附帶換行字元
  • write!:將格式化字串寫入特定的 buffer 物件,但不附帶換行字元

以下實例將錯誤訊息輸出到標準錯誤 (standard error):

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. use std::io::Write;
  2.  
  3. fn main() {
  4.     writeln!(&mut std::io::stderr(), "Error message")
  5.         .expect("Failed to print to stderr");
  6. }

以下實例輸出不同的格式化字串:

Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. fn main() {
  2.     // Hexadeicmal number
  3.     assert_eq!(format!("0x{:X}", 255), "0xFF");
  4.  
  5.     // Octal number
  6.     assert_eq!(format!("0o{:o}", 127), "0o177");
  7.  
  8.     // Decimal with specific precision
  9.     assert_eq!(format!("{:.2}", 3.14159), "3.14");
  10.  
  11.     // Formatted string for debug purpose
  12.     assert_eq!(format!("{:?}", vec![1, 2, 3]), "[1, 2, 3]");
  13.  
  14.     // Formatted string with specific position
  15.     assert_eq!(format!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob"),
  16.                "Alice, this is Bob. Bob, this is Alice");
  17.  
  18.     // Formatted string with specific name
  19.     assert_eq!(format!("{subject} {verb} {object}", object = "the lazy dog",
  20.                        verb = "jumps over", subject = "The swift fox"),
  21.                "The swift fox jumps over the lazy dog");
  22. }

關於作者

位元詩人 (ByteBard) 是資訊領域碩士,喜歡用開源技術來解決各式各樣的問題。這類技術跨平台、重用性高、技術生命長。

除了開源技術以外,位元詩人喜歡日本料理和黑咖啡,會一些日文,有時會自助旅行。