To count the number of occurrences of a specified element in an array in Rust, you can use iterators or loops to iterate through the array and count each occurrence.
In this example,
numbers
with values 10, 20, 30, 40, 30, 50.iter
method to create an iterator over the vector.filter
method on the iterator to filter elements equal to 30.count
method to count the filtered elements.fn main() {
let numbers = vec![10, 20, 30, 40, 30, 50];
let count = numbers.iter().filter(|&x| *x == 30).count();
println!("Number of occurrences of element 30: {}", count);
}
Number of occurrences of element 30: 2
In this example,
fruits
with values 'apple', 'banana', 'cherry', 'banana'.count
to 0 to store the count of occurrences.count
each time element 'banana' is found.count
will contain the total count of occurrences of element 'banana'.fn main() {
let fruits = vec!["apple", "banana", "cherry", "banana"];
let mut count = 0;
for fruit in &fruits {
if fruit == "banana" {
count += 1;
}
}
println!("Number of occurrences of element 'banana': {}", count);
}
Number of occurrences of element 'banana': 2
In this tutorial, we learned How to count the Number of Occurrences of Specified Element in the Array in Rust language with well detailed examples.