Home > database >  Histogram of string in C
Histogram of string in C

Time:02-13

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?

CodePudding user response:

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]);
}

CodePudding user response:

here is another solution:

#include <stdio.h>
#include <string.h>
#include <ctype.h>


void stringHistogram(char *s) {

  size_t len = 0;
  size_t counts[256] = {0};

  len = strlen(s);

  for (size_t ii = 0; ii < len;   ii) {
    size_t idx = (size_t)s[ii];
    if((idx > 64) && (idx < 91)){
      idx  = 32;
    }
    counts[idx]  ;
  }

  for (size_t ii = 0; ii < 255;   ii) {
    if(0 != isprint((char)ii)){
      if (counts[ii] > 0){
        printf("%lu [%c] occurs %lu times.\n", ii, (char)ii, counts[ii]);
      }
    }
  }
  return;
}

int main() {
  char s[] = "!!!!!PrOgraMMing -------iN C Is easy....";
  stringHistogram(s);

  return 0;
}

first like 0___________, I handled upper/lower case while counting, also I used size_t over int (it's an unsigned type)

My output is

32 [ ] occurs 4 times.
33 [!] occurs 5 times.
45 [-] occurs 7 times.
46 [.] occurs 4 times.
97 [a] occurs 2 times.
99 [c] occurs 1 times.
101 [e] occurs 1 times.
103 [g] occurs 2 times.
105 [i] occurs 3 times.
109 [m] occurs 2 times.
110 [n] occurs 2 times.
111 [o] occurs 1 times.
112 [p] occurs 1 times.
114 [r] occurs 2 times.
115 [s] occurs 2 times.
121 [y] occurs 1 times.
  • Related