What is string.is_ascii() in Rust?

Overview

The is_ascii() method in Rust is used to check if the characters of a particular string are ASCII or within the ASCII range. If at least one of the characters is not ASCII, then a Boolean false is returned. Otherwise, a true is returned.

A character is said to be ASCII if it is a number from 0 to 9, a letter from A to Z, or a special character.

Syntax

string.is_ascii()
Syntax to check if a string is ASCII

Parameters

string: This is the string we are checking to see if it is an ASCII.

Return value

The value returned is a boolean. If all the characters of the string are ASCII, a true is returned. Otherwise, false is returned.

Code example

fn main(){
// create some strings
let str1 = "Edpresso is the best";
let str2 = "I love ❤ Educative.io"; // non ASCII
let str3 = "I shine like a star ☀"; // non ASCII
let str4 = "Rust is the best!";
let str5 = "Coding is fun";
// check if stracters are ascii
println!("'{}' is ASCII? {}", str1, str1.is_ascii()); // true
println!("'{}' is ASCII? {}", str2, str2.is_ascii()); // false
println!("'{}' is ASCII? {}", str3, str3.is_ascii()); // false
println!("'{}' is ASCII? {}", str4, str4.is_ascii()); // true
println!("'{}' is ASCII? {}", str5, str5.is_ascii()); // true
}

Code explanation

  • Lines 3–7: We create some strings, out of which a few are ASCII while the others are not.
  • Lines 10–14: We check if the strings are ASCII using the is_ascii() method and then print the result to the console screen.

Free Resources