A character is a whitespace if it is one of the following characters: blank space (‘ ‘), newline (‘\n’), horizontal tab (‘\t’), carriage return (‘\r’), form feed (‘\f’) or vertical tab (‘\v’). The if statement given below tests whether the given character ch is equal to one of these characters using logical or (||) operator and prints an appropriate message.
if (ch == ‘ ‘ || /* ch is a blank space or */
ch == ‘\t’ || /* a horizontal tab or */
ch ==’\n’ || /* a new line or */
ch == ‘\r’ || /* a carriage return or */
ch == ‘\f’ || /* a form feed or */
ch== ‘\v’) /* a vertical tab */
printf(“Whitespace\n”);
else printf(“Not whitespace\n”);
Note that to test for a whitespace, it is often sufficient to check whether the given character is equal to one of three characters: space, horizontal tab and new line, e. g., when the characters are entered from the keyboard. Thus, the above if statement can be rewritten as shown below.
if (ch== ‘ ‘ || ch== ‘\t’ || ch== ‘\n’)
printf(“Whitespace\n”);
else printf(“Not whitespace\n”);
Example: Test for whitespace
#include <stdio.h>
void main()
{
char ch;
clrscr();
Printf(“Enter the Character”);
scanf(“%c”,&ch);
if (ch == ‘ ‘ || /* ch is a blank space or */
ch == ‘\t’ || /* a horizontal tab or */
ch ==’\n’ || /* a new line or */
ch == ‘\r’ || /* a carriage return or */
ch == ‘\f’ || /* a form feed or */
ch== ‘\v’) /* a vertical tab */
printf(“Whitespace\n”);
else printf(“Not whitespace\n”);
getch();
}