国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Rust 標(biāo)準(zhǔn)庫字符串類型String及其46種常用方法

這篇具有很好參考價值的文章主要介紹了Rust 標(biāo)準(zhǔn)庫字符串類型String及其46種常用方法。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

Rust 標(biāo)準(zhǔn)庫字符串類型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)值終止,實際上就是對Vec<u8>的包裝,在堆內(nèi)存上分配一個字符串。

其源代碼大致如下:

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是一個可變引用,而&str是對該字符串的不可變引用,即可以更改String的數(shù)據(jù),但是不能操作&str的數(shù)據(jù)。String包含其數(shù)據(jù)的所有權(quán),而&str沒有所有權(quán),它從另一個變量借用得來。

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)建字符串。實際上復(fù)制了一個新的字符串。

let rust_str = "rust";
let rust_string = String::from(rust_str);

3、使用字符串字面量的to_string將字符串字面量轉(zhuǎn)換為字符串。實際上復(fù)制了一個新的字符串。

let s1 = "rust_to_string";
let s2 = s1.to_string();

to_string()實際上是封裝了String::from()

4、使用{}格式化輸出

let s?= "rust";
print!("{}",s);?

索引和切片

1、String字符串是UTF-8編碼,不提供索引操作。

2、Rust 使用切片來“索引”字符串,[ ] 里不是單個數(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);
    //單個字符只能使用范圍指定,不能僅用一個整數(shù)[1]
    let a = &s[1..2];
    println!("{}", a);
    let a = &s[1..=1];
    println!("{}", a);
    //等價于以下操作:
    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()方法:該方法返回一個迭代器,可以遍歷字符串的Unicode字符。

let s = String::from("Hello, Rust!");
for c in s.chars() {
?   println!("{}", c);
}

.bytes()方法:該方法返回一個迭代器,可以遍歷字符串的字節(jié)序列。

let s = String::from("Hello, Rust!");
for b in s.bytes() {
?   println!("{}", b);
}

.chars().enumerate()方法:該方法返回一個元組迭代器,可以同時遍歷字符和它們在字符串中的索引。

let s = String::from("Hello, Rust!");
for (i, c) in s.chars().enumerate() {
?   println!("{}: {}", i, c);
}

.split()方法:該方法返回一個分割迭代器,可以根據(jù)指定的分隔符將字符串分割成多個子字符串,然后遍歷每個子字符串。

let s = String::from("apple,banana,orange");
for word in s.split(",") {
?   println!("{}", word);
}

.split_whitespace()方法:該方法返回一個分割迭代器,可以根據(jù)空格將字符串分割成多個子字符串,然后遍歷每個子字符串。

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)建一個空的 String 對象。

let s = String::new();

2. from

from():從一個字符串字面量、一個字節(jié)數(shù)組或另一個字符串對象中創(chuàng)建一個新的 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)建一個具有指定容量的 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)前容量小于下限,則這是一個空操作。

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():將一個字符追加到字符串的末尾。

let mut s = String::from("hello");
s.push('!');

9. push_str

push_str():將一個字符串追加到字符串的末尾。

let mut s = String::from("hello");
s.push_str(", world!");

10. pop

pop():將字符串的最后一個字符彈出,并返回它。

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():從字符串的指定位置移除一個字符,并返回它。

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():在字符串的指定位置插入一個字符。

let mut s = String::from("hello");
s.insert(2, 'l');

16.?insert_str

insert_str():在字符串的指定位置插入一個字符串。

let mut s = String::from("hello");
s.insert_str(2, "ll");

17. replace

replace():將字符串中的所有匹配項替換為另一個字符串。

let mut s = String::from("hello, world");
let new_s = s.replace("world", "Rust");

18.?replace_range

replace_range():替換字符串的指定范圍內(nèi)的所有字符為另一個字符串。

let mut s = String::from("hello");
s.replace_range(1..3, "a");

19. split

split():將字符串分割為一個迭代器,每個元素都是一個子字符串。

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():將字符串分割為一個迭代器,每個元素都是一個不包含空格的子字符串。

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():將字符串分成兩個部分,在指定的位置進(jìn)行分割。

let s = String::from("hello");
let (left, right) = s.split_at(2);

22.?split_off

split_off():從字符串的指定位置分離出一個子字符串,并返回新的 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)建一個與原始字符串相同的新字符串。

let s1 = String::from("hello");
let s2 = s1.clone();

28. eq

eq():比較兩個字符串是否相等。

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():查找字符串中第一個匹配指定子字符串的位置。

let s = String::from("hello");
let pos = s.find("l");
assert_eq!(pos, Some(2));

33. rfind

rfind():查找字符串中最后一個匹配指定子字符串的位置。

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():將字符串分割為一個迭代器,每個元素都是一行文本。

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():將字符串分割為一個迭代器,每個元素都是一個字符。

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():將字符串分割為一個迭代器,每個元素都是一個字節(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種方法,更多方法請見官方文檔:

String in std::string - Rust文章來源地址http://www.zghlxwxcb.cn/news/detail-471195.html

到了這里,關(guān)于Rust 標(biāo)準(zhǔn)庫字符串類型String及其46種常用方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • Python標(biāo)準(zhǔn)數(shù)據(jù)類型-字符串常用方法(下)

    Python標(biāo)準(zhǔn)數(shù)據(jù)類型-字符串常用方法(下)

    ?作者簡介:CSDN內(nèi)容合伙人、阿里云專家博主、51CTO專家博主、新星計劃第三季python賽道Top1 ??個人主頁:hacker707的csdn博客 ??系列專欄:零基礎(chǔ)入門篇 ??個人格言:不斷的翻越一座又一座的高山,那樣的人生才是我想要的。這一馬平川,一眼見底的活,我不想要,我的人生

    2024年02月04日
    瀏覽(17)
  • Rust字符串:安全、高效和靈活的數(shù)據(jù)類型

    Rust字符串:安全、高效和靈活的數(shù)據(jù)類型

    Rust是一種現(xiàn)代的系統(tǒng)級編程語言,以其出色的內(nèi)存安全性和高性能而受到廣泛關(guān)注。在Rust中,字符串是一種重要的數(shù)據(jù)類型,它具有獨特的特點,使其在處理文本和字符數(shù)據(jù)時成為理想的選擇。本文將深入探討Rust字符串的特性,包括安全性、高效性和靈活性,以幫助您更好

    2024年01月19日
    瀏覽(23)
  • C# 把字符串(String)格式轉(zhuǎn)換為DateTime類型方法

    Convert.ToDateTime(string)? 注意:string格式有要求,必須是yyyy-MM-dd hh:mm:ss 方式二:DateTime.Parse(string) 參考:將字符串轉(zhuǎn)換為 DateTime | Microsoft Learn DateTime.Tostring()//這個轉(zhuǎn)換之后是YYYY/MM/DD HH:MM:SS DateTime.ToShortString()//這個轉(zhuǎn)換之后是YYYY/MM/DD Convert.ToDateTime(string)//string是你要轉(zhuǎn)換成時間

    2024年02月09日
    瀏覽(25)
  • C++中求string類型字符串長度的三種方法

    C++中求string類型字符串長度的三種方法

    length()函數(shù)是string的內(nèi)置成員方,用于返回string類型字符串的實際長度。 length()函數(shù)聲明: // 返回 string 長度,單位字節(jié) size_t length() const noexcept; 示例1: size()函數(shù)與length()一樣,沒有本質(zhì)區(qū)別。string類剛開始只有l(wèi)ength()函數(shù),延續(xù)了C語言的風(fēng)格。引入STL之后,為了兼容又加入

    2024年02月07日
    瀏覽(26)
  • Python標(biāo)準(zhǔn)數(shù)據(jù)類型-字符串常用方法(下)【文末送書】

    Python標(biāo)準(zhǔn)數(shù)據(jù)類型-字符串常用方法(下)【文末送書】

    ?作者簡介:CSDN內(nèi)容合伙人、阿里云專家博主、51CTO專家博主、新星計劃第三季python賽道Top1 ??個人主頁:hacker707的csdn博客 ??系列專欄:零基礎(chǔ)入門篇 ??個人格言:不斷的翻越一座又一座的高山,那樣的人生才是我想要的。這一馬平川,一眼見底的活,我不想要,我的人生

    2024年02月11日
    瀏覽(27)
  • Python標(biāo)準(zhǔn)數(shù)據(jù)類型-字符串常用方法(上)【文末送書】

    Python標(biāo)準(zhǔn)數(shù)據(jù)類型-字符串常用方法(上)【文末送書】

    ?作者簡介:CSDN內(nèi)容合伙人、阿里云專家博主、51CTO專家博主、新星計劃第三季python賽道Top1 ??個人主頁:hacker707的csdn博客 ??系列專欄:零基礎(chǔ)入門篇 ??個人格言:不斷的翻越一座又一座的高山,那樣的人生才是我想要的。這一馬平川,一眼見底的活,我不想要,我的人生

    2024年02月03日
    瀏覽(26)
  • List<Long> 類型數(shù)據(jù)轉(zhuǎn)為string字符串類型 jdk1.8新特性

    話不多說,直接上代碼 這里,我們首先將 ListLong 轉(zhuǎn)換為 StreamLong ,然后使用 map() 方法將每個 Long 類型的元素轉(zhuǎn)換為字符串類型,再使用 Collectors.joining() 方法將所有字符串連接起來并用逗號和空格分隔。 需要注意的是, Collectors.joining() 方法返回的是一個字符串類型的結(jié)果,

    2024年02月13日
    瀏覽(32)
  • 【Golang】IEEE754標(biāo)準(zhǔn)二進(jìn)制字符串轉(zhuǎn)為浮點類型

    【Golang】IEEE754標(biāo)準(zhǔn)二進(jìn)制字符串轉(zhuǎn)為浮點類型

    ? IEEE 754是一種標(biāo)準(zhǔn),用于表示和執(zhí)行浮點數(shù)運算的方法。在這個標(biāo)準(zhǔn)中,單精度浮點數(shù)使用32位二進(jìn)制表示,分為三個部分:符號位、指數(shù)位和尾數(shù)位。 符號位(s) 用一個位來表示數(shù)的正負(fù),0表示正數(shù),1表示負(fù)數(shù)。 指數(shù)位(e) 用8位表示指數(shù)。對于單精度浮點數(shù),指數(shù)位是以

    2024年01月21日
    瀏覽(24)
  • vue前端判斷某一個String類型的集合中是否包含某一個字符串怎么做

    在上面的代碼中,我們使用 includes() 方法判斷 strList 數(shù)組中是否包含 targetStr 字符串,如果包含則輸出“字符串集合中包含目標(biāo)字符串”,否則輸出“字符串集合中不包含目標(biāo)字符串”。 該博文為原創(chuàng)文章,未經(jīng)博主同意不得轉(zhuǎn)。本文章博客地址:https://cplusplus.blog.csdn.net/a

    2024年02月21日
    瀏覽(96)
  • 考研算法第46天: 字符串轉(zhuǎn)換整數(shù) 【字符串,模擬】

    考研算法第46天: 字符串轉(zhuǎn)換整數(shù) 【字符串,模擬】

    題目前置知識 c++中的string判空 c++中最大最小宏 字符串使用+發(fā)運算將字符加到字符串末尾 ?題目概況 AC代碼

    2024年02月12日
    瀏覽(25)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包