Overview
In this article, you will come to know how to write a c program to count the characters in the string except space. Here, space is nothing but white space or blank space. We know, string in the c programming is nothing but character array.
Also Read: C Program to Display a String in Capital Letters
In this article, I will explain to you two programs. These two programs will be a little bit different.
C Program to Count the Characters in the String Including Space
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[100];
int i=0,count=0;
printf("Enter a String\n");
gets(str);
while(str[i]!='\0')
{
count++;
i++;
}
printf("Total number of characters in %s is %d including space", str, count);
return 0;
}
This is not our actual program. Because we need to count the total number of characters in a string except space. But this program is including space also. I have written this program to only show you the little bit difference.
Also Read: Interview Questions On C
Output of this program
Enter a String
Welcome to C Programming Tutorial
Total number of characters in Welcome to C Programming Tutorial is 33 including space
From this output, it is clear that this program is counting total characters including space. Now, let’s see our next program which is slightly different from this program.
C Program to Count the Characters in the String Except Space
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[100];
int i=0,count=0;
printf("Enter a String\n");
gets(str);
while(str[i]!='\0')
{
if(str[i]!=' ')
{
count++;
}
i++;
}
printf("Total number of characters in %s is %d without space",str,count);
return 0;
}
Just compare both these c programs, you can find one difference and that difference is
if(str[i]!=' ')
{
count++;
}
In the first program, I have added this if statement. In this if statement, I have written one condition and that condition is str[i] is not equal to ‘ ‘. What does this mean? We have declared one character array of size 100. We know that array index is always starts from zero and ends with null character i.e. \0.
Also Read: C Language Program to Count the Number of Lowercase Letters in a Text File
Initially, I have set the value of i = 0 and incrementing this value by 1. So, there is a possibility that we can space i.e. ‘ ‘. Why we have written this two single quotations? Space is also a character and we know, we can write a character constant in a single quotation. So, the value i will be 0, 1, 2, …..
When this if condition is satisfied means when str[i] is not equal to \0, only then we have count the characters. Here, we have taken a variable count to count the total characters.
Now, see the output.
Also Read: C Program to Remove White Spaces and Comments from a File
Enter a String
Welcome to C Programming Tutorial
Total number of characters in Welcome to C Programming Tutorial is 29 Except space
I hope you have understood this program. If you have any difficulties, you can contact me. Thanks for reading.