C Program to count Characters with and without Space

« C Tutorial C Examples »

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:

// Write a program in C to find the number of Characters
// with space and without space in a given String

int main()
    char str[100];
    int i, countWithSpace=0, countWithoutSpace=0;
    printf("Enter any string: ");
    for(i=0; str[i]!='\0'; i++)
    for(i=0; i<countWithSpace; i++)
    countWithoutSpace = countWithSpace-countWithoutSpace;
    printf("\nNumber of character (with space) = %d", countWithSpace);
    printf("\nNumber of character (without space) = %d", countWithoutSpace);
    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:

« C Tutorial C Examples »


Quick Links
Signup - Login - Give Online Test