c program to find length of characters in a string
In this program, you will calculate the length of a character in a string without counting space.
#include<stdio.h>
int main()
{
char a[50];
int c=0,i;
printf("\nenter a string:");
gets(a);
for(i=0;a[i]!='\0';i++)
{
if(a[i]!=' ')
c++;
}
printf("length of character are %d",c);
}
output
enter a string:welcome to Studyfame.com length of character are 22
explanation of character count in the string program
- Take input from a user by using the
gets()method and store value in a variablea. - Iterate the loop from
0to\0(end of a string). - Inside loop check, if the current iteration doesn't contain space then increment
cvalue. variable c is used for counting characters in strings. - After the end of a loop, print the total count of characters in a string.
Count character using while loop
In this C program, you will take input from the user and count the total number of characters in a string by using a while loop.#include<stdio.h>
int main() {
char a[50];
int c = 0, i = 0;
printf("\nenter a string:");
// take input from a user
gets(a);
while (a[i] != '\0') {
if (a[i] != ' '){
c++;
}
i++;
}
printf("length of character in string are: %d", c);
return 0;
}
output
enter a string:studyfame length of character in string are: 9
Count character using do while loop
This program is the same as the above program only here we are using the do-while loop.
#include<stdio.h>
int main() {
char a[50];
int c = 0, i = 0;
printf("\nenter a string:");
gets(a);
do
{
if (a[i] != ' '){
c++;
}
i++;
}while (a[i] != '\0');
printf("length of character in string are: %d", c);
return 0;
}
output
enter a string:learn from studyfame length of character in string are: 18