OneBite.Dev - Coding blog in a bite size

Check If A String Contains Only Numbers In Rust

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

In computer programming, it is often necessary to determine whether a string contains only numerical digits. This article presents a simple guide on how to perform this task in Rust, a statically-typed, high-level programming language designed for performance and safety.

Code Snippet for Checking If a String Contains Only Numbers in Rust

fn is_numeric(s: &str) -> bool {
    s.chars().all(|c| c.is_numeric())
}

fn main() {
    let s = "123456";
    println!("{}", is_numeric(s));
}

Code Explanation for Checking If a String Contains Only Numbers in Rust

In the Rust programming language, to create a function that can check if a string contains only numbers, firstly we define the function is_numeric(). We pass a string slice &str to the function, and it returns a boolean value bool.

fn is_numeric(s: &str) -> bool {
    s.chars().all(|c| c.is_numeric())
}

The s.chars() expression will transform our string slice s into an iterator of its characters, and then we call .all() method on this iterator.

The .all() method is a method available on iterators in Rust, that returns true if all elements of the iterator satisfy the predicate, else, it returns false. It takes a closure, in this case |c| c.is_numeric(), where |c| represents each character c in the provided string.

The method .is_numeric() returns true if the provided character c is a numerical digit and false if it is not.

The function is_numeric() then returns the result, which will be true if every character in the string was a number, and false otherwise.

In the main function:

fn main() {
    let s = "123456";
    println!("{}", is_numeric(s));
}

We define a string s, and then we print the result of calling is_numeric() on s. If the string s contains only numbers, it will print true. Otherwise, it will print false.

And that’s how you can check if a string contains only numbers in Rust.

rust