Check if a character is Space/Whitespace in Arduino

ArduinoArduino BoardsArduino IDEArduino Programming Language

The isSpace() and isWhitespace() functions can be used to check if a character is a space or, more specifically, a whitespace. Whitespace is a subset of space. While whitespace includes only space and horizontal tab (‘\t’), space includes form feed (‘\f’), new line (‘\n’), carriage return (‘\r’) and even vertical tab (‘\v’).

Example

The following example demonstrates the usage of these functions −

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   char c1 = 'a';
   char c2 = ' ';
   char c3 = '\t';
   char c4 = '\n';

   if (isSpace(c1)) {
      Serial.println("c1 is a Space!");
   } else {
      Serial.println("c1 is NOT a Space!");
   }

   if (isWhitespace(c1)) {
      Serial.println("c1 is a Whitespace!");
   } else {
      Serial.println("c1 is NOT a Whitespace!");
   }

   Serial.println();

   if (isSpace(c2)) {
      Serial.println("c2 is a Space!");
   } else {
      Serial.println("c2 is NOT a Space!");
   }

   if (isWhitespace(c2)) {
      Serial.println("c2 is a Whitespace!");
   } else {
      Serial.println("c2 is NOT a Whitespace!");
   }

   Serial.println();

   if (isSpace(c3)) {
      Serial.println("c3 is a Space!");
   } else {
      Serial.println("c3 is NOT a Space!");
   }

   if (isWhitespace(c3)) {
      Serial.println("c3 is a Whitespace!");
   } else {
      Serial.println("c3 is NOT a Whitespace!");
   }

   Serial.println();

   if (isSpace(c4)) {
      Serial.println("c4 is a Space!");
   } else {
      Serial.println("c4 is NOT a Space!");
   }

   if (isWhitespace(c4)) {
      Serial.println("c4 is a Whitespace!");
   } else {
      Serial.println("c4 is NOT a Whitespace!");
   }
   Serial.println();
}

void loop() {
   // put your main code here, to run repeatedly:
}

Output

The Serial Monitor Output is −

As can be seen, while space and tab characters are considered as both a space and whitespace, new line character is considered as space only, and not whitespace. You are encouraged to try this function on other characters as well.

raja
Published on 31-May-2021 14:13:56
Advertisements