How to use isspace function in C programming?

The isspace function in C programming checks whether the argument passed is a white-space character or not. The standard white-space characters are the following: space (' ' ), form feed ('\f' ), new-line ('\n' ), carriage return ('\r' ), horizontal tab ('\t' ), and vertical tab ('\v').

 

List of all standard white-space characters in C programming are:

Character Description
‘ ‘ space
‘\n’ newline
‘\t’ horizontal tab
‘\v’ vertical tab
‘\f’ form feed
‘\r’ Carraige return

 

One thing you should remember is that before using the isspace, you have to include ctype.h because it is declared in ctype.h . The isspace function takes one argument in the form of integer and returns the value of type int.

In the “C” locale, isspace returns true only for the standard white-space characters. Also, if isupper returns a nonzero value, it is guaranteed that isalnum returns zero for the same character in the same locale.

 

Syntax of isspace function in C:

//Syntax of isspace

int isspace(int c);

Parameters:

c => character to classify

Return value:

Non-zero value => If the argument is a whitespace character.
0 => If the argument is neither a whitespace character.

 

Example,

Input : ' '
Output : Non-zero value

Input : a
Output : zero

Input : 1
Output : Zero

Input : @
Output : Zero

Input : '\n'
Output : Non-zero value

 

 

C Program to Check whether a Character Entered by User is a whitespace character or not Using the isspace :

Let’s see a C program to check given character is a whitespace character or not.

#include <stdio.h>
#include <ctype.h>

int main()
{
    unsigned char c = 'A';

    int result = isspace(c);
    result ? printf("A is whitespace char\n"):printf("A is not a whitespace char\n");

    c = ' ';
    result = isspace(c);
    result ? printf("\' ' is whitespace char\n"):printf("\' ' is not a whitespace char\n");

    c = '\n';
    result = isspace(c);

    result ? printf("\\n is whitespace char\n"): printf("\\n is not a control char\n");

    return 0;
}

Output:

isspace function in c

 

Explanation:

As we know that isspace() returns a non-zero value for the whitespace character. So when we pass ‘A‘ to the isspace it returns zero because it is not a whitespace character. But when we pass ‘\n‘ and ' ' it returns a non-zero value and prints the message that it is a whitespace character.

 

Print Count of the whitespace character in given input string:

There are many applications of isspace in C programming. But to find out the count of whitespace characters in a given input stream is very popular. So let’s see a C code to find the count of the whitespace characters in the given input stream.

Algorithm:

1. Traverse the given string character by character and passed it into the isspace function.

2. Increment the counter variable whenever encounter the whitespace letter.

3. Break the loop when encountered the null character (Limitation there must not be another null character in the string except the terminating null character).

4. Return the value of the counter from the function and print the value in the main function.

#include <ctype.h>
#include<string.h>
#include <stdio.h>

unsigned int findCountWhiteSpaceLetterGivenStream(char *str)
{
    unsigned int counter = 0;
    if (str != NULL)
    {
        unsigned int i = 0;
        // counting of control char
        while (str[i] != '\0')
        {
            if (isspace((unsigned char)str[i]))
            {
                ++counter;
            }
            ++i;
        }
    }
    // returning total number of whitespace char
    // present in given input stream
    return (counter);
}

int main()
{
    char str[] = "aticle world .com\n";

    unsigned int counter = findCountWhiteSpaceLetterGivenStream(str);

    printf("Total number of char in input stream is : %u\n\n", strlen(str));

    printf("\nNumber of whitespace char in the "
           "given input stream is : %u\n\n", counter);

    return 0;
}

Output:

Total number of char in input stream is : 11

Number of whitespace char in the given input stream is : 2

 

C program to trim leading/trailing whitespace character in a given string using isspace:

Let’s see another popular program to trim whitespace from the given input string. We will use take the help of the isspace function to identify the whitespace character.

Method 1: If you can modify the input string:

The below function returns a pointer to a substring of the original string. Also If the given string was allocated dynamically, the programmer should use the original pointer to deallocate the allocated memory. They must not be used the return pointer for deallocating the memory.

#include <ctype.h>
#include<string.h>
#include <stdio.h>


char *trimwhitechar(char *str)
{
    if (str != NULL)
    {
        char *end;

        // Trim leading space
        while(isspace((unsigned char)*str))
        {
            ++str;
        }

        if(*str == 0)  // All spaces?
        {
            return str;
        }

        // Trim trailing space
        end = str + strlen(str) - 1;
        while(end > str && isspace((unsigned char)*end))
        {
            end--;
        }

        // Write new null terminator character
        end[1] = '\0';
    }

    return str;
}



int main()
{
    char str[] = "     aticle world .com      ";

    printf("\nString before trimming trailing white space: \n'%s'\n\n", str);

    char *p = trimwhitechar(str);

    printf("\n\nString after trimming trailing white spaces: \n'%s'\n\n", p);

    return 0;
}

Output:

isspace in C

 

Method 2: If you can not modify the input string:

This method is useful when you don’t want to modify the input string. In this method, we store the trimmed input string into the given output buffer, which must be large enough to store the result.

#include <ctype.h>
#include<string.h>
#include <stdio.h>


unsigned int trimwhitechar(char *outputBuffer, unsigned int givenStringLen, const char *str)
{

    unsigned int  outputBufferSize = 0;
    if((str != NULL)
            && (givenStringLen > 0))
    {
        const char *end;

        // Trim leading space
        while(isspace((unsigned char)*str))
            str++;

        if(*str == 0)  // All spaces?
        {
            *outputBuffer = 0;
            outputBufferSize = 1;
        }
        else
        {
            // Trim trailing space
            end = str + strlen(str) - 1;
            while(end > str && isspace((unsigned char)*end))
            {
                end--;
            }
            end++;
            // Set output size to minimum of trimmed string length and buffer size minus 1
            outputBufferSize = ((end - str) < (givenStringLen-1)) ? (end - str) : givenStringLen-1;

            // Copy trimmed string and add null terminator
            memcpy(outputBuffer, str, outputBufferSize);
            outputBuffer[outputBufferSize] = 0;
        }
    }

    return outputBufferSize;
}


int main()
{
    char str[] = "     aticle world .com      ";

    const unsigned int gievenStringSize = sizeof(str);

    char outputBuffer[gievenStringSize];

    printf("\nString before trimming trailing white char: \n'%s'\n\n", str);
    printf("\n\nString len before trimming trailing white char: \n%d\n\n", gievenStringSize);

    unsigned int lenSubString = trimwhitechar(outputBuffer,gievenStringSize,str);

    printf("\n\nString after trimming trailing white char: \n'%s'\n\n", outputBuffer);

    printf("\n\nString len after trimming trailing white char: \n%d\n\n", lenSubString);

    return 0;
}

Output:

isspace char in c

 

Note: If the argument’s value (c) is neither representable as unsigned char not equal to EOF, the behavior of isspace is undefined.

 

As we know the behavior of isspace is undefined if the argument’s value is neither representable as unsigned char nor equal to EOF. So to use these functions safely with plain chars (or signed chars), the argument should first be converted to unsigned char. Because it is good to convert signed char to unsigned char before being assigned or converted to a larger signed type.

int my_isspace(char ch)
{
    return isspace((unsigned char)ch);
}

 

Recommended Post:

Leave a Reply

Your email address will not be published. Required fields are marked *