Rust 中 &str 和 String 方法理解

340 阅读4分钟

在 Rust 编程中,&str 和 String 是常用的字符串类型,它们各自拥有一些独特的方法,同时也有一些共有的方法。理解这些方法的使用场景和差异,对于高效处理字符串至关重要。

一、&str 和 String 共有的方法

  • 说明:这些共有方法提供了字符串的基本操作功能,适用于 &str 的只读场景和 String 的可变场景下的通用操作,如获取长度、判断是否为空、字符和字节的遍历以及子串的查找等。它们是字符串处理的基础工具集,能满足大多数常见的字符串处理需求,且不会改变字符串的基本结构。

  • len() :返回字符串的长度,返回值类型为 usize

  • is_empty() :检查字符串是否为空,返回值类型为 bool

  • chars() :返回一个迭代器,遍历字符串中的字符,返回值类型为 Chars

  • bytes() :返回一个迭代器,遍历字符串中的字节,返回值类型为 Bytes

  • contains(needle) :检查字符串是否包含子串,返回值类型为 bool

  • starts_with(prefix) :检查字符串是否以给定前缀开头,返回值类型为 bool

  • ends_with(suffix) :检查字符串是否以给定后缀结尾,返回值类型为 bool

  • find(needle) :查找子串在字符串中的位置,返回值类型为 Option<usize>

  • rfind(needle) :从字符串末尾开始查找子串的位置,返回值类型为 Option<usize>

  • matches(needle) :查找所有匹配给定模式的子串,返回值类型为 Matches

以下是这些共有方法的示例:

let s = "hello world";
let s_string = s.to_string();

// len()
assert_eq!(s.len(), 11);
assert_eq!(s_string.len(), 11);

// is_empty()
assert_eq!(s.is_empty(), false);
assert_eq!(s_string.is_empty(), false);

// contains()
assert_eq!(s.contains("world"), true);
assert_eq!(s_string.contains("world"), true);

// starts_with()
assert_eq!(s.starts_with("hello"), true);
assert_eq!(s_string.starts_with("hello"), true);

// ends_with()
assert_eq!(s.ends_with("world"), true);
assert_eq!(s_string.ends_with("world"), true);

// find()
assert_eq!(s.find("o"), Some(4));
assert_eq!(s_string.find("o"), Some(4));

// rfind()
assert_eq!(s.rfind("o"), Some(7));
assert_eq!(s_string.rfind("o"), Some(7));

// matches()
let matches_str = s.matches("l").collect::<Vec<_>>();
let matches_string = s_string.matches("l").collect::<Vec<_>>();
assert_eq!(matches_str, ["l", "l"]);
assert_eq!(matches_string, ["l", "l"]);

二、String 特有的方法

  • 说明String 特有的方法主要是基于其可变的特性设计的,用于满足对字符串内容进行修改的需求,如追加、清空、截断、过滤和替换等操作,这些操作会改变字符串本身,而 &str 作为不可变引用无法执行这些操作。

  • push_str(other) :将另一个字符串追加到当前字符串,没有返回值。

  • clear() :清空字符串,没有返回值。

  • truncate(len) :截断字符串到指定长度,没有返回值。

  • retain(predicate) :过滤字符串中的字符,没有返回值。

  • replace(old, new) :替换字符串中的子串,返回值类型为 String

  • trim() :去除字符串两端的空白字符,返回值类型为 String

  • trim_start() :去除字符串开头的空白字符,返回值类型为 String

  • trim_end() :去除字符串末尾的空白字符,返回值类型为 String

以下是 String 特有的方法示例:

let mut s = String::from("hello");

// push_str()
s.push_str(" world");
assert_eq!(s, "hello world");

// replace()
let replaced = s.replace("world", "Rust");
assert_eq!(replaced, "hello Rust");

// trim()
let mut s_with_spaces = String::from("   hello   ");
let trimmed = s_with_spaces.trim();
assert_eq!(trimmed, "hello");

三、&str 特有的方法

  • 说明&str 特有的方法虽然与 String 的部分方法同名,但返回值类型有所不同,这是为了在不改变原字符串的基础上提供一些便捷的操作方式,以适应 &str 不可变的特性,避免不必要的字符串复制,同时也能满足一些特定的字符串处理需求,如获取去掉空白字符后的视图或高效地处理字符串替换操作。

  • trim() :去除字符串两端的空白字符,返回值类型为 &str

  • trim_start() :去除字符串开头的空白字符,返回值类型为 &str

  • trim_end() :去除字符串末尾的空白字符,返回值类型为 &str

  • replace(old, new) :替换字符串中的子串,返回值类型为 Cow<str>(可以是 &str 或 String)。

以下是 &str 特有的方法示例:

let s: &str = "   hello   ";

// trim()
let trimmed = s.trim();
assert_eq!(trimmed, "hello");

// replace()
let replaced: std::borrow::Cow<str> = s.replace("hello", "hi");
assert_eq!(replaced, "   hi   ");

通过对 &str 和 String 方法的详细介绍和示例演示,我们能够更加清晰地了解它们的功能和用法区别。在实际的 Rust 编程中,根据具体的需求选择合适的字符串类型和方法,能够使代码更加简洁、高效和健壮。希望本文能够帮助读者更好地掌握 Rust 字符串处理的技巧,提升编程能力。