I am trying to figure out how to check if a character is equal to white-space in C. I know that tabs are \'\\t\'
and newlines are \'\\n\'
, but I wa
There is no particular symbol for whitespace. It is actually a set of some characters which are:
' ' space
'\t' horizontal tab
'\n' newline
'\v' vertical tab
'\f' feed
'\r' carriage return
Use isspace standard library function from ctype.h if you want to check for any of these white-spaces.
For just a space, use ' '
.
make use of isspace function .
The C library function int isspace(int c) checks whether the passed character is white-space.
sample code:
int main()
{
char var= ' ';
if( isspace(var) )
{
printf("var1 = |%c| is a white-space character\n", var );
}
/*instead you can easily compare character with ' '
*/
}
Standard white-space characters are − ' ' (0x20) space (SPC) '\t' (0x09) horizontal tab (TAB) '\n' (0x0a) newline (LF) '\v' (0x0b) vertical tab (VT) '\f' (0x0c) feed (FF) '\r' (0x0d) carriage return (CR)
source : tutorialpoint
#include <stdio.h>
main()
{
int c,sp,tb,nl;
sp = 0;
tb = 0;
nl = 0;
while((c = getchar()) != EOF)
{
switch( c )
{
case ' ':
++sp;
printf("space:%d\n", sp);
break;
case '\t':
++tb;
printf("tab:%d\n", tb);
break;
case '\n':
++nl;
printf("new line:%d\n", nl);
break;
}
}
}
To check a space symbol you can use the following approach
if ( c == ' ' ) { /*...*/ }
To check a space and/or a tab symbol (standard blank characters) you can use the following approach
#include <ctype.h>
//...
if ( isblank( c ) ) { /*...*/ }
To check a white space you can use the following approach
#include <ctype.h>
//...
if ( isspace( c ) ) { /*...*/ }
The ASCII value of Space
is 32. So you can compare your char to the octal value of 32 which is 40 or its hexadecimal value which is 20.
if(c == '\40')
{ ... }
or
if(c == '\x20')
{ ... }
Any number after the \
is assumed to be octal, if the character just after \
is not x
, in which case it is considered to be a hexadecimal.
The character representation of a Space is simply ' '
.
void foo (const char *s)
{
unsigned char c;
...
if (c == ' ')
...
}
But if you are really looking for all whitespace, then C has a function (actually it's often a macro) for that:
#include <ctype.h>
...
void foo (const char *s)
{
char c;
...
if (isspace(c))
...
}
You can read about isspace
here
If you really want to catch all non-printing characters, the function to use is isprint
from the same library. This deals with all of the characters below 0x20 (the ASCII code for a space) and above 0x7E (0x7f is the code for DEL, and everything above that is an extension).
In raw code this is equivalent to:
if (c < ' ' || c >= 0x7f)
// Deal with non-printing characters.