rust count occurrences of a substring
To count the occurrences of a substring in Rust, you can use the matches
method from the str
type. Here's an example:
fn count_substring_occurrences(string: &str, substring: &str) -> usize {
string.matches(substring).count()
}
fn main() {
let string = "Hello, hello, hello!";
let substring = "hello";
let count = count_substring_occurrences(string, substring);
println!("The substring '{}' occurs {} times in the string.", substring, count);
}
In this example, the count_substring_occurrences
function takes two parameters: string
and substring
. It uses the matches
method to find all occurrences of the substring
in the string
and returns the count.
The main
function demonstrates how to use the count_substring_occurrences
function by counting the occurrences of the substring "hello" in the string "Hello, hello, hello!" and printing the result.
Please let me know if you need further assistance!