We use the isblank()
function in C++ to determine if a given character is a blank character. A blank character is any of the following characters:
' '
: The space character.'\t'
: The tab character.To use the isblank()
function, include the following library:
#include <cctype>
The isblank()
function is declared as follows:
int isblank(int c);
c
: The ASCII value of the character being checked.Note: If
c
is not anunsigned char
orEOF
, the behavior of theisblank()
function is undefined.
isblank()
function returns a non-zero value if c
is a blank.isblank()
function returns 0
if c
is not a blank.Consider the code snippet below, which demonstrates the use of the isblank()
function.
#include <cctype>#include <iostream>using namespace std;int main(){char c1 = 'a';char c2 = ' ';cout<<"'"<<c1<<"' is blank: "<<isblank(c1)<<endl;cout<<"'"<<c2<<"' is blank: "<<isblank(c2)<<endl;return 0;}
Two characters c1
and c2
are declared in lines 7-8. c1
is not a blank and c2
is a blank.
isblank()
function in line 10 to check whether c1
is a blank. The isblank()
function returns 0, which means that c1
is not a blank.isblank()
function in line 11 to check whether c2
is a blank. The isblank()
function returns a non-zero value, which means that c2
is a blank.Consider the code snippet below, which uses the isblank()
function to remove the blanks from other characters in a string.
#include <cctype>#include <cstring>#include <iostream>using namespace std;int main(){char str[] = "H el lo w o r d!! ";int len = strlen(str);char withoutBlanks[len];int blankCount = 0;int ind = 0 ;for(int i = 0; i < len; i++){if( isblank(str[i])==0 ){withoutBlanks[ind] = str[i];ind++;}else{blankCount++;}}withoutBlanks[ind] = '\0';cout<<"string = "<<str<<endl;cout<<"string without blanks = "<<withoutBlanks<<endl;cout<<"number of blanks in string = "<<blankCount<<endl;return 0;}
str
is declared that contains both blank and non-blank characters.withoutBlanks
is declared that will contain the non-blank characters of str
.blankCount
is declared that will contain the count of the number of blank characters of str
.str
such that if a character is a non-blank, it is copied the character in withoutBlanks
. If a character is a blank, add one to blankCount
.Free Resources