Sid5427
Sid5427

Reputation: 743

Is there any way to check if any or all characters are present in a string in C?

I was trying to check and see if I give an array of characters - like this

char  array_values[] = { 'A','B','C','D','a','b','c','d' };

and then running a sort of character matching in multiple strings e.g.-

....
str1 = 'AACDBACBAabcAcddaAABD'
str2 = 'aacbdAABDCAaDDCBCAabc'
....

and then returning a count of each char present in the strings.

I know it's easily done in python, R, perl, but I wanted to figure this out in C. Maybe something like a regular expression? Any ideas?

Upvotes: 2

Views: 905

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

The easiest way to do it in C is to count each character regardless of its presence in the array_values, then use array_values items as indexes into the array of counts to get the results:

int count[256];
for (int i = 0 ; i != 256 ; count[i++] = 0);
// The example works with a single string. For multiple strings,
// iterate over the strings from your source in a loop, assigning str
// and incrementing the counts for each of your strings.
char *str = "AACDBACBAabcAcddaAABD";
for (char *p = str ; *p ; count[(unsigned char)*p++]++);
char array_values[] = { 'A','B','C','D','a','b','c','d' };
for (int i = 0 ; i != 8 ; i++) {
    printf("Found '%c' %d times", array_values[i], count[(unsigned char)array_values[i]]);
}

Here is a demo on ideone.

Upvotes: 4

Related Questions