计算char数组中的字符?

时间:2016-09-14 05:38:53

标签: c char

目前我正在尝试根据每个单词的第一个字符对段落进行排序。我正在初始化两个字母(上部和下部)字符数组,以便将该字的第一个字符与数组索引进行比较。

我的问题计划;

  • 使用Alphabet初始化两个数组以了解哪个字母表在之前。
  • 有一个实际上将第一个char与两个Arrays进行比较的函数。
  • 返回排序的单词:)

我的问题是我试图查看这两个数组是否有26个字符,以确保每个字母都被计算在内但它打印1并且我不知道为什么。

代码:

#include <stdio.h>

int main(int argc, const char * argv[]) {

    char _alphabetUpperCase[100] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R,","S","T","U","V","W","X","Y","Z"};
    char _alpabetLowerCase[100] = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};

    int i = 0;
    int n = 0;
    while(_alpabetLowerCase[i] != NULL)
    {
        n = n+1;
        i++;
    }

    printf("%d\n",n);
    return 0;
}

3 个答案:

答案 0 :(得分:3)

这&#34; A&#34;与&#39; A&#39;不同。你应该指定一个&#39; A&#39;而是一个角色。 替换所有&#34;&#34;字符串与相应的&#39;&#39;字符。 e.g。

char _alpabetLowerCase[100] = {'a','b','c' ... };

答案 1 :(得分:1)

你想要字符或字符串? "a"是一个字符串,而'a'是一个字符。根据你对数组的定义,你似乎想要字符。因此,将此代码更改为

char _alpabetLowerCase[100] = {"a", ...

改为使用

char _alpabetLowerCase[100] = {'a', 'b', ....

答案 2 :(得分:1)

试试这个:

#include <stdio.h>

int main(int argc, const char * argv[]) {
    char _alphabetUpperCase[27] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R,','S','T','U','V','W','X','Y','Z', '\0'};
    char _alphabetLowerCase[27] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', '\0'};

    int i = 0;
    int n = 0;
    while(_alphabetLowerCase[i] != '\0')
    {
        n = n+1;
        i++;
    }

    printf("%d\n",n);
    return 0;
}

说明:'a'是char,但"a"是字符串。另外我添加了第27个字符以确保此循环将在'z'之后停止(因此我将数组大小更改为27(100也是正确的,但是当您可以设置正确的值时写入任意数字是错误的))。