OneBite.Dev - Coding blog in a bite size

Check If A String Contains Only Letters In Rust

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

Rust is an efficient system programming language that offers safety in concurrency and memory. Performing operations like checking if a string contains only letters can be quite valuable for a myriad of applications. Let’s take a dive into a code that allows us to determine if a string in Rust consists of only letters.

Code Snippet

In Rust, you can check if a string contains only letters through methods provided by the char data type. Here is an example:

fn only_letters(input: &str) -> bool {
    input.chars().all(char::is_alphabetic)
}

fn main(){
    let _str = "HelloWorld";
    println!("{}", only_letters(&_str))
}

Code Explanation

This code in Rust checks whether a given string consists of only letters.

Step 1: Begin by defining a function, only_letters, which takes a string slice (&str) as an input. This function returns a boolean value.

fn only_letters(input: &str) -> bool {

Step 2: Inside this function, we are calling the chars method on the input string. The chars method separates the string into a series of characters.

input.chars()

Step 3: Apply the all method on the result. The all method takes a closure, in this case, char::is_alphabetic, which is a built-in method to check if a character is alphabetic. It will return true when all characters are alphabetic and false otherwise.

input.chars().all(char::is_alphabetic)

Step 4: In the main function, we define a string _str and call the only_letters function passing the string reference &_str.

fn main(){
    let _str = "HelloWorld";
    println!("{}", only_letters(&_str));
}

If the string only contains letters, the only_letters function will return true which will then be printed out. Otherwise, it outputs false.

rust