OneBite.Dev - Coding blog in a bite size

Check If A String Contains Only Alphanumeric Characters In Rust

Code snippet for how to Check If A String Contains Only Alphanumeric Characters In Rust with sample and detail explanation

Rust is a powerful programming language known for its safety and speed that’s great for system design. Checking if a string only contains alphanumeric characters can be quite essential for validating user inputs, file naming, and more.

Code snippet for Checking If A String Contains Only Alphanumeric Characters In Rust

Here’s a simple Rust code snippet that confirms if a given string contains only alphanumeric characters:

fn only_alphanumeric(input: &str) -> bool {
    return input.chars().all(|c| c.is_alphanumeric());
}

fn main() {
    let text = "HelloWorld123";
    if only_alphanumeric(&text) {
        println!("The string only contains alphanumeric characters");
    } else {
        println!("The string contains non-alphanumeric characters");
    }
}

Code Explanation for Checking If A String Contains Only Alphanumeric Characters In Rust

In the given code snippet, we first define a function only_alphanumeric that takes a string slice (&str) as input and gives a boolean result. This function employs an inbuilt method in Rust called all. The all method tests if all characters in the iterator satisfy a particular condition, in this case, c.is_alphanumeric(), which is true if c is an alphanumeric character.

Within the main function main, we create a string text that we want to verify. We call our only_alphanumeric function on this text. If the function returns true, that implicitly means that our string text includes only alphanumeric characters and hence we print “The string only contains alphanumeric characters”. Otherwise, we print “The string contains non-alphanumeric characters”.

In sum, we created a handy function that verifies if a string only includes alphanumeric characters, a task that could be used in various scenarios like input validation or maintaining specific string formats. The string verification relies on Rust’s inbuilt methods like all and is_alphanumeric, simplifying our task.

rust