计算数组中字符出现次数

时间:2015-09-28 22:30:23

标签: c arrays loops

很简单,但我遇到了麻烦。我在数组中有一个随机的字母序列:

char box[] = "rbpbymgoybrppogrgxombpgpbpbooyogrrm";

我需要计算某个字母出现的次数(例如字母'r')。

到目前为止,这是我的计划:

main() {
    int count = 0;

    for(int i = 0; i < sizeof(box); i++) {
        if(box[i] == '\r') count++;
    }

    printf("Red: %d", count);
}

现在我已经预感到使用'\ r'来尝试识别角色是什么不起作用。有没有其他方法来表示字符并在数组中检查它们?我是否使用他们的ASCII等价物?

3 个答案:

答案 0 :(得分:2)

'\r'意味着Carriage Return。只需使用'r'

if(box[i] == 'r')

答案 1 :(得分:0)

以下代码将给出输入字符串

中每个字母类型的计数

应该很容易有选择地只打印第二个&#39;中的感兴趣的信件。环

#include <stdio.h>

#define MAX_CHAR_TYPES (256)

static char box[] = "rbpbymgoybrppogrgxombpgpbpbooyogrrm";

static unsigned int charCounts[ MAX_CHAR_TYPES ]= {0};

int main( void )
{
    for(size_t i = 0; i < (sizeof(box)-1); i++)
    {
        charCounts[ (int)box[i] ]++;
    }

    for(int i=0; i < MAX_CHAR_TYPES; i++)
    {
        if( 0 < charCounts[i] )
        {
            printf("There were %d of the %c character\n", charCounts[i], (unsigned int)i);
        }
    }
    return 0;
} // end function: main

答案 2 :(得分:0)

在R Programming Language中,这就是我们得到的

>arr="aaaaafdgshghsghgshfsgfsaaadahsgdhsgdhaaaggghahgahgahghaghhhha"
>arr
#[1] "aaaaafdgshghsghgshfsgfsaaadahsgdhsgdhaaaggghahgahgahghaghhhha"
> aa=strsplit(arr,"")
> aa
#[[1]]
# [1] "a" "a" "a" "a" "a" "f" "d" "g" "s" "h" "g" "h" "s" "g" "h" "g" "s" "h" "f" "s" "g" "f" "s" "a" "a" "a" "d" "a" "h" "s"
#[31] "g" "d" "h" "s" "g" "d" "h" "a" "a" "a" "g" "g" "g" "h" "a" "h" "g" "a" "h" "g" "a" "h" "g" "h" "a" "g" "h" "h" "h" "h"
#[61] "a"
>table(aa[[1]])
#  a  d  f  g  h  s 
#  17  4  3 14 16  7