Rust, Software Development

Rust – How to check if a String is Numeric

Rust Thread Synchronization Barrier validate Email Regular Expressions check String Numeric display content array tuple hashmap vector
Photo by Mike from Pexels

We always work with string values. In Rust, we can check if a string value is numeric or not using the function is_numeric()  on a char value. That means we look at each character within a string.

Rust Codes To Check If String Is Numeric

Since the is_numeric function is only available on a char value, we need to loop through a string to look at each character’s value. To loop through a string, consider the following Rust codes.

When we run these codes, we get the following output.

Now we have access to each character value, and we can run the is_numeric function. Let us change the codes a bit as follows.

When we run these Rust codes, we get a different output. Instead of character on each line, we get “false” (or “true” if a character is numeric).

Let us use a new set of test data. Given the following strings, we want to know if each is numeric and only contains numeric digits.

Since we are dealing with a set of strings now, we need to wrap our Rust codes in a function to reuse them. Consider the following function. We loop through each char value from the input using a for loop with the String.chars()  function. Then, we invoke the is_numeric() function on each char value.

In our main function, we use the function as follows.

When we run the main function, we get the following.

Check If String Is Alphabetic

There is another function on Rust char type that can help us check if a string is numeric. Alternatively, we could use the is_alphabetic function. However, for our purpose, we need to change some logic. So, consider the following changes to our is_string_numeric function.

If a character value is alphabetic, our function will immediately return false. When we run the main function with the changes, we get the same output.

We tested the codes with Rust 1.52.1.

You Might Also Like