Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

rust
character
whitespace
communitycreator

How to check if a character is white space in Rust

okwudili onyejiaku

Overview

A white space character is any character or characters that represent horizontal or vertical space in typography. In Rust, we can check if a character is white space using the is_whitespace() method.

Syntax

character.is_whitespace()
Syntax of the is_whitespace() method

Parameter value

character: This is the character we want to check to see if it is a white space.

Return value

The is_whitespace() method returns a Boolean value. If the character is a white space, then the method returns true. Otherwise, it returns false.

Example

fn main(){
  // create some characters
  let char1 = 'E';
  let char2 = '\u{A0}';   // no-break space
  let char3 = '\n';       // new line
  let char4 = 'r';
  let char5 = '\u{202F}'; // narrow no-break space 

  // check if characters are white-space
  println!("{}", char1.is_whitespace());  // false
  println!("{}", char2.is_whitespace());  // true
  println!("{}", char3.is_whitespace());  // true
  println!("{}", char4.is_whitespace());  // false
  println!("{}", char5.is_whitespace());  // true
}
Check if some characters are white space characters in Rust

Explanation

  • Lines 3–7: We create some characters, some of which are white space.
  • Lines 10–14: We check the characters we created to see if they are white space. Then, we print the results to the console.

RELATED TAGS

rust
character
whitespace
communitycreator
RELATED COURSES

View all Courses

Keep Exploring