Rust中字符串類型String的46種常用方法分享
Rust字符串
Rust主要有兩種類型的字符串:&str和String
&str
由&[u8]表示,UTF-8編碼的字符串的引用,字符串字面值,也稱作字符串切片。&str用于查看字符串中的數(shù)據(jù)。它的大小是固定的,即它不能調(diào)整大小。
String
String 類型來自標(biāo)準(zhǔn)庫,它是可修改、可變長度、可擁有所有權(quán)的同樣使用UTF-8編碼,且它不以空(null)值終止,實(shí)際上就是對Vec<u8>的包裝,在堆內(nèi)存上分配一個(gè)字符串。
其源代碼大致如下:
pub struct String { vec: Vec<u8>, } impl String { pub fn new() -> String { String { vec: Vec::new() } } pub fn with_capacity(capacity: usize) -> String { String { vec: Vec::with_capacity(capacity) } } pub fn push(&mut self, ch: char) { // ... } pub fn push_str(&mut self, string: &str) { // ... } pub fn clear(&mut self) { self.vec.clear(); } pub fn capacity(&self) -> usize { self.vec.capacity() } pub fn reserve(&mut self, additional: usize) { self.vec.reserve(additional); } pub fn reserve_exact(&mut self, additional: usize) { self.vec.reserve_exact(additional); } pub fn shrink_to_fit(&mut self) { self.vec.shrink_to_fit(); } pub fn into_bytes(self) -> Vec<u8> { self.vec } pub fn as_str(&self) -> &str { // ... } pub fn len(&self) -> usize { // ... } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> { // ... } pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> { // ... } } impl Clone for String { fn clone(&self) -> String { String { vec: self.vec.clone() } } fn clone_from(&mut self, source: &Self) { self.vec.clone_from(&source.vec); } } impl fmt::Display for String { // ... } impl fmt::Debug for String { // ... } impl PartialEq for String { // ... } impl Eq for String { // ... } impl PartialOrd for String { // ... } impl Ord for String { // ... } impl Hash for String { // ... } impl AsRef<str> for String { // ... } impl AsRef<[u8]> for String { // ... } impl From<&str> for String { // ... } impl From<String> for Vec<u8> { // ... } // ...
String 和 &str 的區(qū)別
String是一個(gè)可變引用,而&str是對該字符串的不可變引用,即可以更改String的數(shù)據(jù),但是不能操作&str的數(shù)據(jù)。String包含其數(shù)據(jù)的所有權(quán),而&str沒有所有權(quán),它從另一個(gè)變量借用得來。
Rust 的標(biāo)準(zhǔn)庫中還包含其他很多字符串類型,例如:OsString、OsStr、CString、CStr。
創(chuàng)建和輸出
1、使用String::new創(chuàng)建空的字符串。
let empty_string = String::new();
2、使用String::from通過字符串字面量創(chuàng)建字符串。實(shí)際上復(fù)制了一個(gè)新的字符串。
let rust_str = "rust"; let rust_string = String::from(rust_str);
3、使用字符串字面量的to_string將字符串字面量轉(zhuǎn)換為字符串。實(shí)際上復(fù)制了一個(gè)新的字符串。
let s1 = "rust_to_string"; let s2 = s1.to_string();
to_string()實(shí)際上是封裝了String::from()
4、使用{}格式化輸出
let s = "rust"; print!("{}",s);
索引和切片
1、String字符串是UTF-8編碼,不提供索引操作。
2、Rust 使用切片來“索引”字符串,[ ] 里不是單個(gè)數(shù)字而是必須要提供范圍。
范圍操作符: .. 或 ..=
start..end 左開右閉區(qū)間 [start, end)
start..=end 全開區(qū)間 [start, end]
示例:
fn main() { let s = "hello, world"; let a = &s[1..4]; println!("{}", a); let a = &s[1..=4]; println!("{}", a); //單個(gè)字符只能使用范圍指定,不能僅用一個(gè)整數(shù)[1] let a = &s[1..2]; println!("{}", a); let a = &s[1..=1]; println!("{}", a); //等價(jià)于以下操作: println!("{:?}", s.chars().nth(1)); println!("{}", s.chars().nth(1).unwrap()); }
輸出:
ell
ello
e
e
Some('e')
e
拼接和迭代
1、拼接直接使用加號 +
fn main() { let s1 = String::from("hello"); let s2 = String::from("world"); let s = s1 + ", " + &s2 ; println!("{}", s); }
輸出:
hello, world
2、各種遍歷(迭代)
.chars()方法:該方法返回一個(gè)迭代器,可以遍歷字符串的Unicode字符。
let s = String::from("Hello, Rust!"); for c in s.chars() { println!("{}", c); }
.bytes()方法:該方法返回一個(gè)迭代器,可以遍歷字符串的字節(jié)序列。
let s = String::from("Hello, Rust!"); for b in s.bytes() { println!("{}", b); }
.chars().enumerate()方法:該方法返回一個(gè)元組迭代器,可以同時(shí)遍歷字符和它們在字符串中的索引。
let s = String::from("Hello, Rust!"); for (i, c) in s.chars().enumerate() { println!("{}: {}", i, c); }
.split()方法:該方法返回一個(gè)分割迭代器,可以根據(jù)指定的分隔符將字符串分割成多個(gè)子字符串,然后遍歷每個(gè)子字符串。
let s = String::from("apple,banana,orange"); for word in s.split(",") { println!("{}", word); }
.split_whitespace()方法:該方法返回一個(gè)分割迭代器,可以根據(jù)空格將字符串分割成多個(gè)子字符串,然后遍歷每個(gè)子字符串。
let s = String::from("The quick brown fox"); for word in s.split_whitespace() { println!("{}", word); }
3. 使用切片循環(huán)輸出
fn main() { let s = String::from("The quick brown fox"); let mut i = 0; while i < s.len() { print!("{}", &s[i..=i]); i += 1; } println!(); while i > 0 { i -= 1; print!("{}", &s[i..=i]); } println!(); loop { if i >= s.len() { break; } print!("{}", &s[i..i+1]); i += 1; } println!(); }ox
輸出:
The quick brown fox
xof nworb kciuq ehT
The quick brown fox
String除了以上這幾種最基本的操作外,標(biāo)準(zhǔn)庫提供了刪增改等等各種各樣的方法以方便程序員用來操作字符串。以下歸納了String字符串比較常用的46種方法:
String 方法
1. new
new():創(chuàng)建一個(gè)空的 String 對象。
let s = String::new();
2. from
from():從一個(gè)字符串字面量、一個(gè)字節(jié)數(shù)組或另一個(gè)字符串對象中創(chuàng)建一個(gè)新的 String 對象。
let s1 = String::from("hello"); let s2 = String::from_utf8(vec![104, 101, 108, 108, 111]).unwrap(); let s3 = String::from(s1);
3. with_capacity
with_capacity():創(chuàng)建一個(gè)具有指定容量的 String 對象。
let mut s = String::with_capacity(10); s.push('a');
4. capacity
capacity():返回字符串的容量(以字節(jié)為單位)。
let s = String::with_capacity(10); assert_eq!(s.capacity(), 10);
5. reserve
reserve():為字符串預(yù)留更多的空間。
let mut s = String::with_capacity(10); s.reserve(10);
6. shrink_to_fit
shrink_to_fit():將字符串的容量縮小到它所包含的內(nèi)容所需的最小值。
let mut s = String::from("foo"); s.reserve(100); assert!(s.capacity() >= 100); s.shrink_to_fit(); assert_eq!(3, s.capacity());
7. shrink_to
shrink_to():將字符串的容量縮小到指定下限。如果當(dāng)前容量小于下限,則這是一個(gè)空操作。
let mut s = String::from("foo"); s.reserve(100); assert!(s.capacity() >= 100); s.shrink_to(10); assert!(s.capacity() >= 10); s.shrink_to(0); assert!(s.capacity() >= 3);
8. push
push():將一個(gè)字符追加到字符串的末尾。
let mut s = String::from("hello"); s.push('!');
9. push_str
push_str():將一個(gè)字符串追加到字符串的末尾。
let mut s = String::from("hello"); s.push_str(", world!");
10. pop
pop():將字符串的最后一個(gè)字符彈出,并返回它。
let mut s = String::from("hello"); let last = s.pop();
11. truncate
truncate():將字符串截短到指定長度,此方法對字符串的分配容量沒有影響。
let mut s = String::from("hello"); s.truncate(2); assert_eq!("he", s); assert_eq!(2, s.len()); assert_eq!(5, s.capacity());
12. clear
clear():將字符串清空,此方法對字符串的分配容量沒有影響。
let mut s = String::from("foo"); s.clear(); assert!(s.is_empty()); assert_eq!(0, s.len()); assert_eq!(3, s.capacity());
13. remove
remove():從字符串的指定位置移除一個(gè)字符,并返回它。
let mut s = String::from("hello"); let second = s.remove(1);
14. remove_range
remove_range():從字符串的指定范圍刪除所有字符。
let mut s = String::from("hello"); s.remove_range(1..3);
15. insert
insert():在字符串的指定位置插入一個(gè)字符。
let mut s = String::from("hello"); s.insert(2, 'l');
16. insert_str
insert_str():在字符串的指定位置插入一個(gè)字符串。
let mut s = String::from("hello"); s.insert_str(2, "ll");
17. replace
replace():將字符串中的所有匹配項(xiàng)替換為另一個(gè)字符串。
let mut s = String::from("hello, world"); let new_s = s.replace("world", "Rust");
18. replace_range
replace_range():替換字符串的指定范圍內(nèi)的所有字符為另一個(gè)字符串。
let mut s = String::from("hello"); s.replace_range(1..3, "a");
19. split
split():將字符串分割為一個(gè)迭代器,每個(gè)元素都是一個(gè)子字符串。
let s = String::from("hello, world"); let mut iter = s.split(", "); assert_eq!(iter.next(), Some("hello")); assert_eq!(iter.next(), Some("world")); assert_eq!(iter.next(), None);
20. split_whitespace
split_whitespace():將字符串分割為一個(gè)迭代器,每個(gè)元素都是一個(gè)不包含空格的子字符串。
let s = String::from(" ? hello ? world ? "); let mut iter = s.split_whitespace(); assert_eq!(iter.next(), Some("hello")); assert_eq!(iter.next(), Some("world")); assert_eq!(iter.next(), None);
21. split_at
split_at():將字符串分成兩個(gè)部分,在指定的位置進(jìn)行分割。
let s = String::from("hello"); let (left, right) = s.split_at(2);
22. split_off
split_off():從字符串的指定位置分離出一個(gè)子字符串,并返回新的 String 對象。
let mut s = String::from("hello"); let new_s = s.split_off(2);
23. len
len():返回字符串的長度(以字節(jié)為單位)。
let s = String::from("hello"); assert_eq!(s.len(), 5);
24. is_empty
is_empty():檢查字符串是否為空。
let s = String::from(""); assert!(s.is_empty());
25. as_bytes
as_bytes():將 String 對象轉(zhuǎn)換為字節(jié)數(shù)組。
let s = String::from("hello"); let bytes = s.as_bytes();
26. into_bytes
into_bytes():將 String 對象轉(zhuǎn)換為字節(jié)向量。
let s = String::from("hello"); let bytes = s.into_bytes(); assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
27. clone
clone():創(chuàng)建一個(gè)與原始字符串相同的新字符串。
let s1 = String::from("hello"); let s2 = s1.clone();
28. eq
eq():比較兩個(gè)字符串是否相等。
let s1 = String::from("hello"); let s2 = String::from("hello"); assert!(s1.eq(&s2));
29. contains
contains():檢查字符串是否包含指定的子字符串。
let s = String::from("hello"); assert!(s.contains("ell"));
30. starts_with
starts_with():檢查字符串是否以指定的前綴開頭。
let s = String::from("hello"); assert!(s.starts_with("he"));
31. ends_with
ends_with():檢查字符串是否以指定的后綴結(jié)尾。
let s = String::from("hello"); assert!(s.ends_with("lo"));
32. find
find():查找字符串中第一個(gè)匹配指定子字符串的位置。
let s = String::from("hello"); let pos = s.find("l"); assert_eq!(pos, Some(2));
33. rfind
rfind():查找字符串中最后一個(gè)匹配指定子字符串的位置。
let s = String::from("hello"); let pos = s.rfind("l"); assert_eq!(pos, Some(3));
34. trim
trim():刪除字符串兩端的所有空格。
let s = String::from(" ? hello ? "); let trimmed = s.trim();
35. trim_start
trim_start():刪除字符串開頭的所有空格。
let s = String::from(" ? hello ? "); let trimmed = s.trim_start();
36. trim_end
trim_end():刪除字符串末尾的所有空格。
let s = String::from(" ? hello ? "); let trimmed = s.trim_end();
37. to_lowercase
to_lowercase():將字符串中的所有字符轉(zhuǎn)換為小寫。
let s = String::from("HeLLo"); let lower = s.to_lowercase();
38. to_uppercase
to_uppercase():將字符串中的所有字符轉(zhuǎn)換為大寫。
let s = String::from("HeLLo"); let upper = s.to_uppercase();
39. retain
retain():保留滿足指定條件的所有字符。
let mut s = String::from("hello"); s.retain(|c| c != 'l');
40. drain
drain():從字符串中刪除指定范圍內(nèi)的所有字符,并返回它們的迭代器。
let mut s = String::from("hello"); let mut iter = s.drain(1..3); assert_eq!(iter.next(), Some('e')); assert_eq!(iter.next(), Some('l')); assert_eq!(iter.next(), None);
41. lines
lines():將字符串分割為一個(gè)迭代器,每個(gè)元素都是一行文本。
let s = String::from("hello\nworld"); let mut iter = s.lines(); assert_eq!(iter.next(), Some("hello")); assert_eq!(iter.next(), Some("world")); assert_eq!(iter.next(), None);
42. chars
chars():將字符串分割為一個(gè)迭代器,每個(gè)元素都是一個(gè)字符。
let s = String::from("hello"); let mut iter = s.chars(); assert_eq!(iter.next(), Some('h')); assert_eq!(iter.next(), Some('e')); assert_eq!(iter.next(), Some('l')); assert_eq!(iter.next(), Some('l')); assert_eq!(iter.next(), Some('o')); assert_eq!(iter.next(), None);
43. bytes
bytes():將字符串分割為一個(gè)迭代器,每個(gè)元素都是一個(gè)字節(jié)。
let s = String::from("hello"); let mut iter = s.bytes(); assert_eq!(iter.next(), Some(104)); assert_eq!(iter.next(), Some(101)); assert_eq!(iter.next(), Some(108)); assert_eq!(iter.next(), Some(108)); assert_eq!(iter.next(), Some(111)); assert_eq!(iter.next(), None);
44. as_str
as_str():將 String 對象轉(zhuǎn)換為字符串切片。
let s = String::from("hello"); let slice = s.as_str();
45. as_mut_str
as_mut_str():將 String 對象轉(zhuǎn)換為可變字符串切片。
let mut s = String::from("foobar"); let s_mut_str = s.as_mut_str(); s_mut_str.make_ascii_uppercase(); assert_eq!("FOOBAR", s_mut_str);
46. remove_matches
remove_matches():刪除字符串中所有匹配的子串。
#![feature(string_remove_matches)] ?//使用不穩(wěn)定的庫功能,此行必須 let mut s = String::from("Trees are not green, the sky is not blue."); s.remove_matches("not "); assert_eq!("Trees are green, the sky is blue.", s);
String字符串包括但不限于此46種方法,更多方法請見官方文檔:
以上就是Rust中字符串類型String的46種常用方法分享的詳細(xì)內(nèi)容,更多關(guān)于Rust String的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Rust中non_exhaustive的enum使用確保程序健壯性
這篇文章主要為大家介紹了Rust中non_exhaustive的enum使用確保程序健壯性示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11Rust結(jié)構(gòu)體的定義與實(shí)例化詳細(xì)講解
結(jié)構(gòu)體是一種自定義的數(shù)據(jù)類型,它允許我們將多個(gè)不同的類型組合成一個(gè)整體。下面我們就來學(xué)習(xí)如何定義和使用結(jié)構(gòu)體,并對比元組與結(jié)構(gòu)體之間的異同,需要的可以參考一下2022-12-12rust實(shí)現(xiàn)post小程序(完整代碼)
這篇文章主要介紹了rust實(shí)現(xiàn)一個(gè)post小程序,本文通過示例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-04-04詳解Rust編程中的共享狀態(tài)并發(fā)執(zhí)行
雖然消息傳遞是一個(gè)很好的處理并發(fā)的方式,但并不是唯一一個(gè),另一種方式是讓多個(gè)線程擁有相同的共享數(shù)據(jù),本文給大家介紹Rust編程中的共享狀態(tài)并發(fā)執(zhí)行,感興趣的朋友一起看看吧2023-11-11Rust使用lettre實(shí)現(xiàn)郵件發(fā)送功能
這篇文章主要為大家詳細(xì)介紹了Rust如何使用lettre實(shí)現(xiàn)郵件發(fā)送功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-11-11Rust開發(fā)WebAssembly在Html和Vue中的應(yīng)用小結(jié)(推薦)
這篇文章主要介紹了Rust開發(fā)WebAssembly在Html和Vue中的應(yīng)用,本文將帶領(lǐng)大家在普通html上和vue手腳架上都來運(yùn)行wasm的流程,需要的朋友可以參考下2022-08-08詳解rust?自動(dòng)化測試、迭代器與閉包、智能指針、無畏并發(fā)
這篇文章主要介紹了rust?自動(dòng)化測試、迭代器與閉包、智能指針、無畏并發(fā),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-11-11