First Occurrence of a Character in a C-String

I am writing a code that takes a cstring from the user and outputs the number of words and the number of occurrences of each letter. It works, but at the end of the program while it is printing the number of occurrences, I would like for it to only print the number of occurrences of each character once. For example, if the cstring has the letter b occur 3 times, it needs to say "3b" rather than "3b 3b 3b". Any suggestions on how I can do this? Here is the main function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
        char text[100];
	int numOfWords = 1;
	cout << "Enter a line of text.\n";
	cin.getline(text, 100);
	for (int i = 0; i < strlen(text); i++)
		text[i] = tolower(text[i]);
	for (int i = 0; i < strlen(text); i++)
	{
		if (isspace(text[i]))
			numOfWords++;
	}
	cout << numOfWords << " word(s)\n";
	for (int i = 0; i < strlen(text); i++)
	{
		int counter = 0;
		for (int y = 0; y < strlen(text); y++)
		{
			if (text[i] == text[y])
				counter++;
		}
		if (isalpha(text[i]))
			cout << counter << " " << text[i] << endl;
	}
	return 0;
One way is to use an array (or map) to store the number of occurrences of each character. You can use the character as the index. First you loop over the string and for each character you increment the counter for that character. Then you loop over the array and print all the characters and counter where the counter is larger than 0.
Last edited on
Your code is invalid in the very beginning when you try to count words

1
2
3
4
5
	for (int i = 0; i < strlen(text); i++)
	{
		if (isspace(text[i]))
			numOfWords++;
	}


The code does not count words. It counts spaces. For example in the string literal "__a" where underscores denote blanks you will count two words though there is only one word "a".
Topic archived. No new replies allowed.