Abeer
Abeer

Reputation: 69

Counting characters in char array?

Currently i'm trying to sort a paragraph based on first char of each word. I'm initializing two alphabetic (Upper and Lower) char arrays to compare to the first char of the word to the array index.

My Plan for the problem;

My problem is i'm trying to see if the two arrays have 26 characters to make sure every alphabet is counted for but it prints 1 and i have no idea why.

Code:

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

Upvotes: 0

Views: 2544

Answers (3)

Ilya
Ilya

Reputation: 4689

Try this:

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

Explanation: 'a' is char, but "a" is string. Also I added 27-th character to become sure that this loop will stop after 'z' (so I changed the array size to 27 (100 was correct too, but it is wrong to write arbitrary numbers when you can put correct value)).

Upvotes: 1

Rohan
Rohan

Reputation: 53316

You want characters or strings? "a" is a string while 'a' is a character. From your definition of array it seems you want characters. So change your code for that as

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

Instead use

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

Upvotes: 1

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

This "A" is not same as 'A'. You should assign 'A' to a character instead. Replace all "" strings with corresponding '' characters. e.g.

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

Upvotes: 3

Related Questions