2015-09-28 37 views
-2

非常简单,但我遇到了麻烦。我有一个数组中的随机字母序列:计算阵列中出现的字符数

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等价物吗?

+0

'的sizeof(盒子)'不是你期望它做的。使用'strlen(box)'获取存储在数组中的**字符串**的长度,而不是**数组**中的条目总数。如果您没有看到区别,请阅读C字符串以及它们与'char'数组(和'char *')的关系。 – Olaf

+0

这段代码不会编译,首先,因为main()总是返回一个'int'。并且因为printf()的调用需要声明:'#include ' – user3629249

+0

还没有触及#include 但是在读完它之后,strlen函数听起来更合适。 – Jertise

回答

2

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

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

我看......没有涉及到那个术语......我通常使用反斜线来识别数组中的整数,但我没有意识到它与字符不一样。 – Jertise

+1

为什么你会使用反斜线来识别数组中的整数? –

+0

我不确定...我只是假设它是如何工作的哈哈。所以我猜它对整数的作用方式相同?我可以使用'34'而不是'\ 34'? – Jertise

0

下面的代码将给每个字母类型的计数输入字符串

它应该很容易选择性地只打印在第二次加息的信“for”循环

#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 
+1

'charCounts [(unsigned char)box [i]] ++;'如果字符串具有负值的字符将更加谨慎。应该使用'UCHAR_MAX + 1'而不是'256'。 –

0

一个R编程语言,这就是我们得到

>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 
相关问题