
- Rust 教程
- Rust - 首頁
- Rust - 簡介
- Rust - 環境搭建
- Rust - HelloWorld 示例
- Rust - 資料型別
- Rust - 變數
- Rust - 常量
- Rust - 字串
- Rust - 運算子
- Rust - 決策
- Rust - 迴圈
- Rust - 函式
- Rust - 元組
- Rust - 陣列
- Rust - 所有權
- Rust - 借用
- Rust - 切片
- Rust - 結構體
- Rust - 列舉
- Rust - 模組
- Rust - 集合
- Rust - 錯誤處理
- Rust - 泛型
- Rust - 輸入輸出
- Rust - 檔案輸入/輸出
- Rust - 包管理器
- Rust - 迭代器和閉包
- Rust - 智慧指標
- Rust - 併發
- Rust 有用資源
- Rust - 快速指南
- Rust - 有用資源
- Rust - 討論
Rust - 字串
Rust 中的字串資料型別可以分為以下幾種:
字串字面量(&str)
字串物件(String)
字串字面量
字串字面量 (&str) 用於在編譯時已知字串值的情況。字串字面量是一組字元,硬編碼到變數中。例如,let company="Tutorials Point"。字串字面量位於模組 std::str 中。字串字面量也稱為字串切片。
以下示例聲明瞭兩個字串字面量:company 和 location。
fn main() { let company:&str="TutorialsPoint"; let location:&str = "Hyderabad"; println!("company is : {} location :{}",company,location); }
字串字面量預設情況下是靜態的。這意味著字串字面量在整個程式的執行期間都保證有效。我們也可以像下面這樣顯式地將變數指定為靜態的:
fn main() { let company:&'static str = "TutorialsPoint"; let location:&'static str = "Hyderabad"; println!("company is : {} location :{}",company,location); }
以上程式將生成以下輸出:
company is : TutorialsPoint location :Hyderabad
字串物件
String 物件型別在標準庫中提供。與字串字面量不同,String 物件型別不是核心語言的一部分。它在標準庫中定義為公共結構 pub struct String。String 是一個可增長的集合。它是可變的,並且是 UTF-8 編碼型別。String 物件型別可用於表示在執行時提供的字串值。String 物件在堆上分配。
語法
要建立 String 物件,我們可以使用以下任何語法:
String::new()
以上語法建立了一個空字串
String::from()
這將建立一個帶有某些預設值的字串,這些預設值作為引數傳遞給 from() 方法。
以下示例說明了 String 物件的使用。
fn main(){ let empty_string = String::new(); println!("length is {}",empty_string.len()); let content_string = String::from("TutorialsPoint"); println!("length is {}",content_string.len()); }
以上示例建立了兩個字串:使用 new 方法建立的空字串物件,以及使用 from 方法從字串字面量建立的字串物件。
輸出如下所示:
length is 0 length is 14
常用方法 - 字串物件
序號 | 方法 | 簽名 | 描述 |
---|---|---|---|
1 | new() | pub const fn new() → String | 建立一個新的空 String。 |
2 | to_string() | fn to_string(&self) → String | 將給定值轉換為 String。 |
3 | replace() | pub fn replace<'a, P>(&'a self, from: P, to: &str) → String | 用另一個字串替換模式的所有匹配項。 |
4 | as_str() | pub fn as_str(&self) → &str | 提取包含整個字串的字串切片。 |
5 | push() | pub fn push(&mut self, ch: char) | 將給定的字元追加到此 String 的末尾。 |
6 | push_str() | pub fn push_str(&mut self, string: &str) | 將給定的字串切片追加到此 String 的末尾。 |
7 | len() | pub fn len(&self) → usize | 返回此 String 的長度(以位元組為單位)。 |
8 | trim() | pub fn trim(&self) → &str | 返回刪除前導和尾隨空格的字串切片。 |
9 | split_whitespace() | pub fn split_whitespace(&self) → SplitWhitespace | 按空格拆分字串切片並返回迭代器。 |
10 | split() | pub fn split<'a, P>(&'a self, pat: P) → Split<'a, P> , where P is pattern can be &str, char, or a closure that determines the split. | 返回此字串切片的子字串的迭代器,這些子字串由模式匹配的字元分隔。 |
11 | chars() | pub fn chars(&self) → Chars | 返回字串切片中字元的迭代器。 |
示例:new()
使用 new() 方法建立一個空字串物件,並將它的值設定為 hello。
fn main(){ let mut z = String::new(); z.push_str("hello"); println!("{}",z); }
輸出
以上程式生成以下輸出:
hello
示例:to_string()
要訪問 String 物件的所有方法,請使用 to_string() 函式將字串字面量轉換為物件型別。
fn main(){ let name1 = "Hello TutorialsPoint , Hello!".to_string(); println!("{}",name1); }
輸出
以上程式生成以下輸出:
Hello TutorialsPoint , Hello!
示例:replace()
replace() 函式接受兩個引數:第一個引數是要搜尋的字串模式,第二個引數是要替換的新值。在以上示例中,Hello 在 name1 字串中出現兩次。
replace 函式將字串 Hello 的所有出現替換為 Howdy。
fn main(){ let name1 = "Hello TutorialsPoint , Hello!".to_string(); //String object let name2 = name1.replace("Hello","Howdy"); //find and replace println!("{}",name2); }
輸出
以上程式生成以下輸出:
Howdy TutorialsPoint , Howdy!
示例:as_str()
as_str() 函式提取包含整個字串的字串切片。
fn main() { let example_string = String::from("example_string"); print_literal(example_string.as_str()); } fn print_literal(data:&str ){ println!("displaying string literal {}",data); }
輸出
以上程式生成以下輸出:
displaying string literal example_string
示例:push()
push() 函式將給定的字元追加到此 String 的末尾。
fn main(){ let mut company = "Tutorial".to_string(); company.push('s'); println!("{}",company); }
輸出
以上程式生成以下輸出:
Tutorials
示例:push_str()
push_str() 函式將給定的字串切片追加到 String 的末尾。
fn main(){ let mut company = "Tutorials".to_string(); company.push_str(" Point"); println!("{}",company); }
輸出
以上程式生成以下輸出:
Tutorials Point
示例:len()
len() 函式返回字串中字元的總數(包括空格)。
fn main() { let fullname = " Tutorials Point"; println!("length is {}",fullname.len()); }
輸出
以上程式生成以下輸出:
length is 20
示例:trim()
trim() 函式刪除字串中前導和尾隨空格。請注意,此函式不會刪除內聯空格。
fn main() { let fullname = " Tutorials Point \r\n"; println!("Before trim "); println!("length is {}",fullname.len()); println!(); println!("After trim "); println!("length is {}",fullname.trim().len()); }
輸出
以上程式生成以下輸出:
Before trim length is 24 After trim length is 15
示例:split_whitespace()
split_whitespace() 將輸入字串拆分為不同的字串。它返回一個迭代器,因此我們像下面這樣遍歷標記:
fn main(){ let msg = "Tutorials Point has good t utorials".to_string(); let mut i = 1; for token in msg.split_whitespace(){ println!("token {} {}",i,token); i+=1; } }
輸出
token 1 Tutorials token 2 Point token 3 has token 4 good token 5 tutorials
示例:split() 字串
split() 字串 方法返回字串切片的子字串的迭代器,這些子字串由模式匹配的字元分隔。split() 方法的限制是結果不能儲存以供以後使用。collect 方法可用於將 split() 返回的結果儲存為向量。
fn main() { let fullname = "Kannan,Sudhakaran,Tutorialspoint"; for token in fullname.split(","){ println!("token is {}",token); } //store in a Vector println!("\n"); let tokens:Vec<&str>= fullname.split(",").collect(); println!("firstName is {}",tokens[0]); println!("lastname is {}",tokens[1]); println!("company is {}",tokens[2]); }
以上示例在遇到逗號 (,) 時拆分字串 fullname。
輸出
token is Kannan token is Sudhakaran token is Tutorialspoint firstName is Kannan lastname is Sudhakaran company is Tutorialspoint
示例:chars()
可以使用 chars 方法訪問字串中的單個字元。讓我們考慮一個示例來理解這一點。
fn main(){ let n1 = "Tutorials".to_string(); for n in n1.chars(){ println!("{}",n); } }
輸出
T u t o r i a l s
使用 + 運算子連線字串
可以將字串值附加到另一個字串。這稱為連線或插值。字串連線的結果是一個新的字串物件。+ 運算子在內部使用 add 方法。add 函式的語法接受兩個引數。第一個引數是 self - 字串物件本身,第二個引數是第二個字串物件的引用。如下所示:
//add function add(self,&str)->String { // returns a String object }
示例:字串連線
fn main(){ let n1 = "Tutorials".to_string(); let n2 = "Point".to_string(); let n3 = n1 + &n2; // n2 reference is passed println!("{}",n3); }
輸出將如下所示
TutorialsPoint
示例:型別轉換
以下示例說明了如何將數字轉換為字串物件:
fn main(){ let number = 2020; let number_as_string = number.to_string(); // convert number to string println!("{}",number_as_string); println!("{}",number_as_string=="2020"); }
輸出將如下所示
2020 true
示例:Format! 宏
將 String 物件組合在一起的另一種方法是使用名為 format 的宏函式。Format! 的用法如下所示。
fn main(){ let n1 = "Tutorials".to_string(); let n2 = "Point".to_string(); let n3 = format!("{} {}",n1,n2); println!("{}",n3); }
輸出將如下所示
Tutorials Point