0

我仍在学习 C,并且一直在尝试找出计算数组中字符出现次数的最佳方法。

我计划将它分成函数并对其进行大量扩展,但到目前为止,我想出的最好的工作代码是一个更大的版本:

#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;
}

从这里我应该得到如下所示的东西:

美国广播公司

2 1 4

我只是想知道是否有一种更简单的方法可以在我开始使用此方法之前有人可以指出我或给我一个示例。

4

3 回答 3

1

您可以尝试将此函数作为所有数组大小的示例插入:

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

使用有意义的名称命名变量是一种更好的做法。对于您和其他可以阅读您的代码的人来说,这将更容易阅读。

于 2013-10-10T13:05:17.683 回答
0

如果您使用计数排序,您将获得更少的代码:

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");
于 2013-10-10T13:04:42.473 回答
0

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]);
    }
  }
}
于 2013-10-10T13:11:42.730 回答