前言
在 Rust 中,&str 和 String 是用于处理字符串的两种主要类型。&str 是一个字符串切片,通常用于不可变的字符串引用,而 String 是一个可变的、堆分配的字符串。以下是它们的一些常用方法及其说明:
&str 常用方法
-
len- 返回字符串的字节长度。
-
let s = "hello"; println!("{}", s.len()); // 输出: 5
-
is_empty- 检查字符串是否为空。
-
let s = ""; println!("{}", s.is_empty()); // 输出: true
-
contains- 检查字符串是否包含指定的子字符串。
-
let s = "hello world"; println!("{}", s.contains("world")); // 输出: true
-
starts_with/ends_with- 检查字符串是否以指定的前缀或后缀开始或结束。
-
let s = "hello world"; println!("{}", s.starts_with("hello")); // 输出: true println!("{}", s.ends_with("world")); // 输出: true
-
find- 返回子字符串第一次出现的字节索引。
-
let s = "hello world"; if let Some(index) = s.find("world") { println!("{}", index); // 输出: 6 }
-
split/split_whitespace- 按指定的分隔符分割字符串,返回一个迭代器。
-
let s = "hello world"; for word in s.split_whitespace() { println!("{}", word); }
-
trim- 去除字符串两端的空白字符。
-
let s = " hello "; println!("'{}'", s.trim()); // 输出: 'hello'
-
to_lowercase/to_uppercase- 返回字符串的小写或大写版本。
-
let s = "Hello"; println!("{}", s.to_lowercase()); // 输出: hello
String 常用方法
-
new- 创建一个新的空
String。 -
let s = String::new();
- 创建一个新的空
-
from- 从一个字符串切片创建一个新的
String。 -
let s = String::from("hello");
- 从一个字符串切片创建一个新的
-
push/push_str- 向字符串末尾添加一个字符或字符串切片。
-
let mut s = String::from("hello"); s.push(' '); s.push_str("world"); println!("{}", s); // 输出: hello world
-
pop- 移除并返回字符串末尾的字符。
-
let mut s = String::from("hello"); s.pop(); println!("{}", s); // 输出: hell
-
insert/insert_str- 在指定索引位置插入一个字符或字符串切片。
-
let mut s = String::from("hello"); s.insert(5, ','); s.insert_str(6, " world"); println!("{}", s); // 输出: hello, world
-
remove- 移除并返回字符串中指定位置的字符。
-
let mut s = String::from("hello"); s.remove(0); println!("{}", s); // 输出: ello
-
replace/replacen- 返回一个新的字符串,其中的所有或前 n 个匹配的子字符串被替换。
-
let s = String::from("hello world"); let new_s = s.replace("world", "Rust"); println!("{}", new_s); // 输出: hello Rust
-
clear- 清空字符串,使其长度为 0。
-
let mut s = String::from("hello"); s.clear(); println!("{}", s); // 输出: (空字符串)
共同方法
-
as_str- 将
String转换为&str。 -
let s = String::from("hello"); let slice: &str = s.as_str();
- 将
-
to_string- 将
&str转换为String。 -
let s = "hello"; let string = s.to_string();
- 将
-
format!- 格式化字符串并返回一个
String。 -
let name = "world"; let s = format!("Hello, {}!", name); println!("{}", s); // 输出: Hello, world!
- 格式化字符串并返回一个
这些方法让你可以方便地操作和管理字符串数据,根据需要选择合适的类型和方法可以帮助你编写高效和清晰的代码。