Reputation: 21
I'm still learning C and I've been trying to figure out the best way to count occurrences of characters in an array.
I plan on separating it into functions and expanding on it a lot but so far the best working code I've come up with is a bigger version of this:
#define SIZEONE 7
#define SIZETWO 3
int main(void)
{
int arrOne[SIZEONE] = {97, 97, 98, 99, 99, 99, 99};
char arrTwo[SIZETWO] = {'a', 'b', 'c'};
int arrThree[SIZETWO] = {0};
int countOne = 0;
int countTwo = 0;
int countThree = 0;
for(countOne = 0; countOne < SIZEONE; countOne++)
{
for(countTwo = 0; countTwo < SIZETWO; countTwo++)
{
if(arrOne[countOne] == arrTwo[countTwo])
{
arrThree[countTwo] = arrThree[countTwo] + 1;
}
}
}
for(countThree = 0; countThree < SIZETWO; countThree++)
{
printf("%c ",arrTwo[countThree]);
}
countThree = 0;
printf("\n");
for(countThree = 0; countThree < SIZETWO; countThree++)
{
printf("%d ",arrThree[countThree]);
}
return 0;
}
From this I should get something that looks like:
a b c
2 1 4
I'm just wondering if there is a simpler way to do this that someone can point me towards or give me an example of before I start using this method.
Upvotes: 0
Views: 216
Reputation: 33273
If you use counting sort you get less code:
long count[1u << CHAR_BIT];
char *text = "The string we want to count characters in";
long i;
// Clear count array
memset(count, 0, sizeof(count));
// Count characters
for (i = strlen(text) - 1; i >= 0; i--) {
count[(unsigned char)text[i]]++;
}
// Print occurance:
for (i = 0; i < 1u << CHAR_BIT; i++) {
if (count[i] > 0) {
printf("%4c", i);
}
}
printf("\n");
for (i = 0; i < 1u << CHAR_BIT; i++) {
if (count[i] > 0) {
printf("%4ld", count[i]);
}
}
printf("\n");
Upvotes: 0
Reputation: 8313
best way is to define a counting array of 256 (or 127 for ascii only) zero it and for each occurrence increment to counting array.
void count_chars(char* arr)
{
int counting[256],i;
memset(counting,0,sizeof(counting));
for(i=0; arr[i];++i){
++counting[(unsigned char)arr[i]];
}
for(i=0; i<256;++i){
if(counting[i]){
printf("%c - %d\n", (char)i, counting[i]);
}
}
}
Upvotes: 0
Reputation: 5014
You can try to insert this function as an example for all array sizes :
int findOccurences(const char *array, const int array_size, const char ch_to_find)
{
int found = 0;
for(int i = 0; i < array_size; ++i)
{
if(array[i] == ch_to_find) found++;
}
return found;
}
It's a better practice to name your variables with a significant name. This will be easier to read for you and for others that can read your code.
Upvotes: 1