C program to count characters with and without space

In this article, we will learn how to count and print the total number of characters present in any given string (provided by the user at run-time) with and without spaces.

Let's create a program that will count and print the total number of characters present inside any given string, with and without spaces. Here is the program:

#include<stdio.h>
#include<conio.h>
int main()
{
    char str[100];
    int i, countWithSpace=0, countWithoutSpace=0;
    printf("Enter any string: ");
    gets(str);
    for(i=0; str[i]!='\0'; i++)
    {
        countWithSpace++;
    }
    for(i=0; i<countWithSpace; i++)
    {
        if(str[i]==32)
            countWithoutSpace++;
    }
    countWithoutSpace = countWithSpace-countWithoutSpace;
    printf("\nNumber of character (with space) = %d", countWithSpace);
    printf("\nNumber of character (without space) = %d", countWithoutSpace);
    getch();
    return 0;
}

As the program was written in the Code::Blocks IDE, here is the sample run after a successful build and run. This is the first snapshot:

count character with space c

Now you can supply any string.say Hi, this is codescracker and press the ENTER key to see the total number of characters, with and without spaces, in the given string, as shown here in the second snapshot:

count character without space c

Here are some of the main steps used in the above program:

C Quiz


« Previous Program Next Program »


Liked this post? Share it!