Rust 從基礎到實踐(5)
字串在 rust 是一個物件特殊型別,所以單拿出來進行分享。可以將字串瞭解為char 的集合。
字串型別由 Rust 的標準庫提供,而不是編碼為核心語言,是一種可增長、可變、擁有的、UTF-8 編碼的字串型別.
字串建立
let mut s = String::new(); let data = "initial contents"; let s = data.to_string();
- 建立一個空的字串(String)
- 然後將資料載入到字串中
let hello = String::from("Hello"); println!("{}",hello);
也可以使用 String::from(資料) 來直接建立字串。
字串的追加內容
let mut hello = String::from("Hello"); println!("{}",hello); hello.push('W'); println!("Length: {}", hello.len() )
字串可以理解為字元集合,我們通過 push 為字串新增字元,但是不可以使用 push 新增字串。不然就會丟擲下面的異常
let mut hello = String::from("Hello"); println!("{}",hello); hello.push('Wo'); println!("Length: {}", hello.len() ) //get length
error: character literal may only contain one codepoint: 'Wo'
我們可以使yong push_str 來為字串新增字串
let mut s1 = String::from("foo"); let s2 = "bar"; s1.push_str(s2); println!("s2 is {}", s2);
字串重新賦值
hello.push_str("orld!");
如果要字串重新賦值時候,如果將字串 hello 修改可變型別,需要新增 mut
let mut hello = "Hello";
字串的合併
let s1 = String::from("Hello, "); let s2 = String::from("world!"); let s3 = s1 + &s2; //
字串的長度
assert_eq!(3, s.len());

螢幕快照 2019-03-09 下午3.53.06.png