Search For A Character In A String In Rust
Code snippet for how to Search For A Character In A String In Rust with sample and detail explanation
One of the frequently used functionalities in the world of programming is searching for a particular character in a string. This article provides a simple illustration of how to do this in Rust, a robust and efficient system programming language.
Example: Searching for a Character in a String in Rust
Firstly, let’s create a simple string in Rust, then find a particular character within it. The following snippet shows how you can perform this operation:
fn main() {
let string = "Hello, World!";
let character = 'W';
let position = string.find(character);
match position {
Some(index) => println!("Character found at position {}", index),
None => println!("Character not found"),
}
}
Code Explanation for Searching for a Character in a String in Rust
-
fn main() {}
- This is the main function where our program starts. -
let string = "Hello, World!";
- Here, we’re creating a string variable namedstring
and giving it the value “Hello, World!“. -
let character = 'W';
- This is the character we’re planning to search for in the string. -
let position = string.find(character);
- Here, we make use of thefind()
method. This builtin method, when invoked on a string, takes in a character and finds the first occurrence of the character in the string, returning its position in the form of anOption<usize>
. If the character is not found,find()
will returnNone
. -
match position {...}
- We then perform a match operation on the result returned byfind()
. -
Some(index) => println!("Character found at position {}", index),
- Iffind()
returns aSome
variant (i.e., it has found the character within the string and returned its index), we print the position. -
None => println!("Character not found"),
- If thefind()
method returnsNone
(which means it didn’t find the character), we print “Character not found”.
To summarise, this simple Rust program searches for a specific character in a given string and displays the position of the character if found, or a not found message if it isn’t present.