How to count the amount of times a specific character appears in an array in C? -
so trying count amount of times specific character occurs in program. example, if entered, abcda, want program print, "there 2 a's." code follows:
int main(void) { char array[10000]; printf("enter input: \n"); scanf("%s", array); printf("array entered is: %s\n", array); char a; //variable want count char *k //used loop int a_counter; //number of times a, occurs fgets(array, sizeof(array), stdin); = fgetc(stdin); a_counter = 0; for(k = array; *k; k++) { if (*k == a) { a_counter++; } } printf("number of a's: %d\n", a_counter); return 0; }
the following loop found on forum attempted count specific character can not seem mine work. approach @ wrong? out of main confused on how so. appreciate given. thank you.
new attempt @ count loop not working. got rid of fgets because confusing me.
int a_counter = 0; if (array == 'a') { a_counter++; } printf("number of a's: %d\n", a_counter);
attempt after @bjorn help.
#include <stdio.h> int main(void) { char array[1000]; printf("enter input: \n); scanf("%s", array); printf("input is: %s\n", array); int c,n =0; while((c = getchar()) != eof) if (c = 'a') n++; printf("amount of a's is: %d\n", n); return 0; }
kism - keep simple, mate :) code way complicated simple task. here's alternative, illustrates mean:
#include <stdio.h> int main(void) { int c, n = 0; while ((c = getchar()) != eof) if (c == 'a') n++; printf("where %d characters\n", n); return 0; }
Comments
Post a Comment