Click here to Skip to main content
15,880,967 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
hi I have to write a program that gets a string and tells the number of its characters .
like my string is "aaabb" , the program's output should be :
a : 3
b : 2


idk how to write it :(

What I have tried:

#include<stdio.h>
int main()
{
	char a[50],ch;
	int i,j,n=0;
	printf("enter your string :\t");
	gets(a);
	for(i=0;a[i]!='\0';i++){
		for(j=0;a[j]!='\0';j++){
			if(a[i]==a[j])
			n++;
		}
	printf(" %c : %d \n",j,n);
}	
}
Posted
Updated 24-May-21 21:10pm
Comments
PIEBALDconsult 11-Nov-17 10:51am    
ASCII only? Or do you need to support "wide" characters?
Do you know whether or not the string is sorted?
At any rate, I recommend iterating the string only once, counting the number of each character as you go. You'll want a place to store the counts.

1 solution

Few modifications should do the job.
C++
#include<stdio.h>
int main()
{
	char a[50],ch;
	int i,j,n=0;
	printf("enter your string :\t");
	gets(a);
	for(i=0;a[i]!='\0';i++){
                n=0; //reset the count for next character in queue
		for(j=0;a[j]!='\0';j++){
			if(a[i]==a[j])
			n++;
		}
	   printf(" %c : %d \n",i,n);//show i instead of j
        }	
}


You'll still be seeing duplicate lines as you are iterating for each characters in the string without checking for duplicates. To overcome this, you can apply logic to have a string with unique characters and that you need to use for outer loop (i).

Check following links for help regarding that-
C program to remove all repeated characters in a string - Codeforwin[^]
Remove all duplicates from a given string - GeeksforGeeks[^]

Hop, it helps :)
 
Share this answer
 
Comments
Member 13515388 11-Nov-17 11:35am    
thanks a lot :))
Suvendu Shekhar Giri 11-Nov-17 11:37am    
Please accept as solution if it helps :)
Member 13515388 11-Nov-17 11:42am    
of course i will
Member 13515388 11-Nov-17 11:41am    
sorry but i don't understand why you put n=0 in the first for
Suvendu Shekhar Giri 11-Nov-17 11:51am    
so that when we iterate for next character, it will start counting again from 1 not the count of previous character.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900