是否可以使诸如“G”的字符串等于50之类的特定数字?

时间:2016-03-23 21:43:03

标签: c

例如,如果我在一个数组中有字母“B”并且想要计算它有多少,我可以使“B”= 1,这样我就可以轻松计算b的数量。我不认为这是类型转换因为我不想让“B”本身= int B

1 个答案:

答案 0 :(得分:2)

您不需要分配字符串,只需使用普通变量。

int b_count = 0;
char *string = "This is a B and this is another B";
for (char *p = string; *p != 0; p++) {
    if (*p == 'B') {
        b_count++;
    }
}
printf("There are %d B's in the string\n", b_count);