C Program to count Characters with and without Space

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

Let's create a program that will count and print the total number of characters present inside any given string with space and without space both. 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 under Code::Blocks IDE, therefore here is the sample run after successful build and run. This is the first snapshot:

count character with space c

Now supply any string say Hi, this is codescracker and press 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 above program:

  • Declare and initialize any two variable say countWithSpace and countWithoutSpace with 0. The first one refers to the total number of characters present inside the string with space and the second one refers to the total number of characters present inside the string without space
  • Receive any string in str
  • Create a for loop that runs from first character to the last
  • Inside the loop, increase the variable say countWithSpace each and every time when program flow enters inside the loop
  • When the null terminated character ('\0') comes as a character inside the string, then nothing left inside the string and program flow goes out from the first for loop
  • Now countWithSpace variable holds the value of string length
  • And to count character without space, we have to check how many spaces are present inside the string
  • Then subtract total character (countWithSpace holds the value of total character) with spaces, that will be the number of character without space
  • Therefore, initialize it to countWithoutSpace variable
  • Finally print the value of both the variable say countWithSpace and countWithoutSpace

C Online Test


« Previous Program Next Program »

Follow/Like Us on Facebook




Subscribe Us on YouTube