Course contentsShow
← C
Lesson 842 of 1,21912. The Standard LibraryFree lesson

Identifying whitespace with `isspace`

Identifying whitespace with isspace

What you'll learn: How to use the isspace function to detect tabs, newlines, and spaces within your text data.

The invisible characters

When we think of "text," we usually focus on letters and numbers. However, the empty gaps between those characters are just as important for a computer to understand. In C, "whitespace" isn't just the spacebar key; it is a category that includes horizontal tabs (\t), newlines (\n), carriage returns (\r), and vertical tabs.

Manually checking if a character matches every single one of these types using if statements would be tedious and error-prone. This is where the <ctype.h> library helps us with a dedicated tool: isspace.

How isspace works

Think of isspace as a specialized filter. You hand it a single character, and it returns a "true" value (a non-zero integer) if the character is any form of whitespace, or "false" (zero) if it is a visible character like 'A', '5', or '$'.

Imagine you are sorting through a bowl of alphabet soup and you want to find all the pieces that are just plain broth bubbles rather than noodle letters. The isspace function is your tool to identify those "empty" gaps.

Code example

To use this function, you must include the header file #include <ctype.h>. Here is how you might use it to count how many gaps are in a specific string:

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

int main() {
    char message[] = "Hello\tWorld\nC is fun!";
    int space_count = 0;

    for (int i = 0; message[i] != '\0'; i++) {
        // isspace returns non-zero if it's a space, tab, or newline
        if (isspace(message[i])) {
            space_count++;
        }
    }

    printf("Total whitespace characters found: %d\n", space_count);
    return 0;
}

In the example above, isspace correctly identifies the tab after "Hello," the newline after "World," and the spaces between the words. It treats all of them as part of the same "whitespace" family, allowing you to process text layout without worrying about which specific type of gap you've encountered.

Key takeaway

The isspace function provides a clean, portable way to detect spaces, tabs, and newlines by returning a non-zero value for any whitespace character.