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種方法,更多方法請見官方文檔:文章來源:http://www.zghlxwxcb.cn/news/detail-471195.html
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)!