OneBite.Dev - Coding blog in a bite size

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

  1. fn main() {} - This is the main function where our program starts.

  2. let string = "Hello, World!"; - Here, we’re creating a string variable named string and giving it the value “Hello, World!“.

  3. let character = 'W'; - This is the character we’re planning to search for in the string.

  4. let position = string.find(character); - Here, we make use of the find() 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 an Option<usize>. If the character is not found, find() will return None.

  5. match position {...} - We then perform a match operation on the result returned by find().

  6. Some(index) => println!("Character found at position {}", index), - If find() returns a Some variant (i.e., it has found the character within the string and returned its index), we print the position.

  7. None => println!("Character not found"), - If the find() method returns None (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.

rust