最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Rust中字符串類型String的46種常用方法分享

 更新時間:2023年06月04日 11:41:25   作者:Hann?Yang  
Rust主要有兩種類型的字符串:&str和String,本文主要為大家介紹的是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

以上就是Rust中字符串類型String的46種常用方法分享的詳細(xì)內(nèi)容,更多關(guān)于Rust String的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Rust搭建webserver的底層原理與應(yīng)用實戰(zhàn)技巧

    Rust搭建webserver的底層原理與應(yīng)用實戰(zhàn)技巧

    本文介紹Rust在HTTP編程中的應(yīng)用,涵蓋協(xié)議基礎(chǔ)、標(biāo)準(zhǔn)庫與第三方庫(如hyper、reqwest)的使用,以及多線程服務(wù)器和線程池的實現(xiàn)與關(guān)閉機制,展示Rust在性能、安全和并發(fā)方面的優(yōu)勢,感興趣的朋友跟隨小編一起看看吧
    2025-06-06
  • 使用?Rust?實現(xiàn)的基礎(chǔ)的List?和?Watch?機制示例流程

    使用?Rust?實現(xiàn)的基礎(chǔ)的List?和?Watch?機制示例流程

    本文給大家介紹使用Rust實現(xiàn)的基礎(chǔ)的List和Watch機制示例流程,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2025-09-09
  • 詳解Rust 修改源

    詳解Rust 修改源

    這篇文章主要介紹了Rust 修改源的相關(guān)知識,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2024-01-01
  • 詳解rust?自動化測試、迭代器與閉包、智能指針、無畏并發(fā)

    詳解rust?自動化測試、迭代器與閉包、智能指針、無畏并發(fā)

    這篇文章主要介紹了rust?自動化測試、迭代器與閉包、智能指針、無畏并發(fā),本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-11-11
  • rust 中的 EBNF簡介舉例

    rust 中的 EBNF簡介舉例

    這篇文章主要介紹了rust 中的 EBNF簡介舉例,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2025-05-05
  • 深入理解 Rust 中的模式匹配語法(最新推薦)

    深入理解 Rust 中的模式匹配語法(最新推薦)

    Rust中的模式匹配提供了多種方式來處理不同的數(shù)據(jù)類型和場景,本文給大家介紹Rust 中的模式匹配語法,感興趣的朋友一起看看吧
    2025-03-03
  • Rust for循環(huán)語法糖背后的API場景分析

    Rust for循環(huán)語法糖背后的API場景分析

    for語句是一種能確定循環(huán)次數(shù)的循環(huán),for 語句用于執(zhí)行代碼塊指定的次數(shù),今天通過本文給大家介紹Rust for循環(huán)語法糖背后的API場景分析,感興趣的朋友跟隨小編一起看看吧
    2022-11-11
  • Rust操作Redis從入門到生產(chǎn)級應(yīng)用

    Rust操作Redis從入門到生產(chǎn)級應(yīng)用

    本文將基于主流的redis-rs庫,帶你全面掌握Rust操作Redis的技巧,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2026-05-05
  • Rust常用特型之Drop特型

    Rust常用特型之Drop特型

    本文主要介紹了Rust常用特型之Drop特型,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-03-03
  • 如何在Rust中處理命令行參數(shù)和環(huán)境變量

    如何在Rust中處理命令行參數(shù)和環(huán)境變量

    在本章節(jié)中, 我們探討了Rust處理命令行參數(shù)的常見的兩種方式和處理環(huán)境變量的兩種常見方式,感興趣的朋友一起看看吧
    2023-12-12

最新評論

大冶市| 威宁| 木里| 甘泉县| 太原市| 齐齐哈尔市| 南康市| 大荔县| 台东县| 宾川县| 克拉玛依市| 仙桃市| 利津县| 淳安县| 搜索| 阳原县| 道真| 贵定县| 利津县| 维西| 黎平县| 利川市| 太原市| 保亭| 津市市| 张家口市| 古浪县| 弥渡县| 湖南省| 清河县| 屏山县| 仙游县| 色达县| 广宗县| 祁东县| 怀安县| 宝丰县| 陕西省| 鄂托克前旗| 精河县| 博爱县|