'Histogram of string in C
I need to find how many times letters appear in string. But I need to ignore the difference between lowercase and uppercase letters.
#include <stdio.h>
#include <string.h>
void stringHistogram(char *s) {
int i, len = 0, counts[256] = {0};
len = strlen(s);
for (i = 0; i < len; i++) {
counts[(s[i])]++;
}
for (i = 65; i < 123; i++) {
if(i>=91&&i<=96)continue;
if (counts[i] > 0)
printf("%c occurs %d times.\n", i, counts[i]);
}
}
int main() {
char s[] = "!!!!!PrOgraMMing -------iN C Is easy....";
stringHistogram(s);
return 0;
}
For example in this string "I" appears once and "i" appears twice. I want to add these two numbers and print number of them as one character. Program output should be "I appears 3 times." Could you help me modify these code?
Solution 1:[1]
You do not need to use strlen and then iterate the string again. Use the correct type for sizes.
void stringHistogram(const char *s)
{
size_t counts[256] = {0};
while(*s) counts[toupper((unsigned char)*s++)] += 1;
for(size_t i = 0; i < sizeof(counts) / sizeof(counts[0]); i++)
if (counts[i] > 0)
printf("%3zu (`%c`) occurs %zu times.\n", i, isprint((unsigned char)i) ? (char)i : '.', counts[i]);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 0___________ |
