In this post, you will learn how to create a program that displays the count of each character in a string in a tabular form.
Let's write a C program c program to display the count of each character in a string.
C Program to Display Count of Each Character in a String
Let's create a file named counteachchar.c and add the following source code to it:
#include<stdio.h>
# include<string.h>
int ifexists(char u, char p[], int v, int q[])
{
int i;
for (i=0; i<=v;i++)
{
if (p[i]==u)
{
q[i]++;
return (1);
}
}
if(i>v) return (0);
}
void main()
{
char str[80],chr[80];
int n,i,x,count[80];
printf("Enter a string: ");
scanf("%s",str);
n=strlen(str);
chr[0]=str[0];
count[0]=1;
x=0;
for(i=1;i < n; i++)
{
if(!ifexists(str[i], chr, x, count))
{
x++;
chr[x]=str[i];
count[x]=1;
}
}
printf("The count of each character in the string %s is \n", str);
for (i=0;i<=x;i++)
printf("%c\t%d\n",chr[i],count[i]);
}
To compile and run the above C program, you can use C Programs Compiler Online tool.
Output:
Enter a string: sourcecodeexamples.net
The count of each character in the string sourcecodeexamples.net is
s 2
o 2
u 1
r 1
c 2
e 5
d 1
x 1
a 1
m 1
p 1
l 1
. 1
n 1
t 1
Comments
Post a Comment