乐闻世界logo
搜索文章和话题

Rust 如何检查字符串是否包含子字符串?

1 个月前提问
1 个月前修改
浏览次数32

1个答案

1

在Rust中,检查一个字符串是否包含另一个字符串可以使用标准库中的str类型的contains方法。这是一种简单且直接的方式来进行字符串包含关系的检查。

如何使用contains方法

contains方法可以接受一个参数,这个参数是你想要检查的子字符串。如果主字符串包含这个子字符串,它将返回true,否则返回false

示例代码

rust
fn main() { let string = "Hello, world!"; let substring = "world"; let result = string.contains(substring); println!("Does the string contain the substring? {}", result); }

在这个例子中,我们检查"Hello, world!"是否包含子字符串"world"。程序会输出true,因为"world"确实是"Hello, world!"的一个子部分。

注意事项

  • contains方法是区分大小写的,这意味着"hello""Hello"被视为不同的字符串。
  • 如果需要进行不区分大小写的检查,你可能需要将两个字符串都转换为小写(或大写)然后再调用contains方法。
rust
fn main() { let string = "Hello, world!"; let substring = "World"; let result = string.to_lowercase().contains(&substring.to_lowercase()); println!("Does the string contain 'World' (case insensitive)? {}", result); }

总结

使用contains方法是Rust中检查字符串包含关系的一种直接且有效的方法。这种方法适用于大多数基本的用例,并且可以通过简单的调整来支持如不区分大小写的检查等更复杂的需求。

2024年8月7日 17:16 回复

你的答案