isspace() in C++ and its application to count whitespace characters

isspace() function
In C++, isspace is a predefined function used for string and character handling.cstring is the header file required for string functions and cctype is the headerfile required for character functions.

This function is used to check if the arguement contains any whitespace characters.
There are many types of whitespace characters in c++ such as-

  • ‘ ‘ – Space
  • ‘\t’ – Horizontal tab
  • ‘\n’ – Newline
  • ‘\v’ – Vertical tab
  • ‘\f’ – Feed
  • ‘\r’ – Carriage return
Syntax
int isspace(int x)

Application
Given a string, we need to count the number of whitespace characters in the string using isspace() function.

Examples:

Input : string = 'Geeks for geeks'
Output :2

Input :string = 'My name is Ayush'
Output :3

Algorithm
1. Traverse the given string character by character upto its length, check if character is a whitespace character.
2. If it is a whitespace character, increment the counter by 1, else traverse to the next character.
3. Print the value of the counter.

// CPP program to count white spaces in a string
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;

// function to calculate whitespaces
void space(string& str)
{
    int count = 0;
    int length = str.length();
    for (int i = 0; i < length; i++) {
        int c = str[i];
        if (isspace(c))
            count++;
    }
    cout << count;
}

// Driver Code
int main()
{
    string str = "Geeks for geeks";
    space(str);
    return 0;
}

Output:

2

This article is contributed by Ayush Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:







Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.