How to check if a character is white space in Rust
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 characterslet char1 = 'E';let char2 = '\u{A0}'; // no-break spacelet char3 = '\n'; // new linelet char4 = 'r';let char5 = '\u{202F}'; // narrow no-break space// check if characters are white-spaceprintln!("{}", char1.is_whitespace()); // falseprintln!("{}", char2.is_whitespace()); // trueprintln!("{}", char3.is_whitespace()); // trueprintln!("{}", char4.is_whitespace()); // falseprintln!("{}", char5.is_whitespace()); // true}
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.