Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

rust
character
ascii
ascii range
communitycreator

How to check if a character is within the ASCII range in Rust

okwudili onyejiaku

Overview

ASCII stands for American Standard Code for Information Interchange. It was the first encoding among others such as the UTF-8, ISO-8859-1, and so on. It is a way to encode a character set used for communication between computers.

A character is said to be in the range of ASCII if it is a number from 0 to 9 or a letter A to Z, or if it's some special character. We can use the is_ascii() method to check if a character is within the ASCII range.

Syntax

character.is_ascii();
Syntax for is_ascii() method

Parameters

character: This is the character we want to check if it is an ASCII in Rust.

Return value

The value returned is a boolean. If the character falls within the ASCII range, a true is returned, otherwise false.

Example

fn main(){
  // create some characters
  let char1 = 'E';
  let char2 = '❤';   // non ASCII
  let char3 = '☀';  // non ASCII
  let char4 = '7';
  let char5 = '!';

  // check if characters are ascii
  println!("{} is ASCII? {}", char1, char1.is_ascii());  // false
  println!("{} is ASCII? {}", char2, char2.is_ascii());  // false
  println!("{} is ASCII? {}", char3, char3.is_ascii());  // true
  println!("{} is ASCII? {}", char4, char4.is_ascii());  // true
  println!("{} is ASCII? {}", char5, char5.is_ascii());  // true
}
Check if a character in Rust is ASCII

Explanation

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

RELATED TAGS

rust
character
ascii
ascii range
communitycreator
RELATED COURSES

View all Courses

Keep Exploring