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

How to check if a string contains a substring in Rust?

1个答案

1

In Rust, checking if a string contains another string can be done using the contains method of the str type in the standard library. This is a simple and straightforward approach for verifying string containment.

How to Use the contains Method

The contains method takes a single parameter, which is the substring you want to check. It returns true if the main string contains this substring, and false otherwise.

Example Code

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

In this example, we check if "Hello, world!" contains the substring "world". The program outputs true because "world" is indeed a substring of "Hello, world!".

Important Notes

  • The contains method is case-sensitive, meaning that "hello" and "Hello" are treated as distinct strings.
  • For case-insensitive checks, you may need to convert both strings to lowercase (or uppercase) before invoking 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); }

Summary

Using the contains method is a direct and effective way to check for string containment in Rust. This approach works for most basic use cases and can be easily adapted to handle more complex requirements, such as case-insensitive checks.

2024年8月7日 17:16 回复

你的答案