简体   繁体   中英

C - Count number of chars in array of strings

I've been working in a program in order to complete Project Euler's problem 17 and I tried to do it in C. Problem:

If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?

I wrote a function that puts all the numbers between 1 and 1000 in words and into an array with 1001 elements (the last is NULL for iteration). But I'm having trouble when I try to count the number of chars in every element of the string, because I don't know how to do it. Can someone give me a little help?

You could do it like this:

int char_count = 0;

char **p = array;

while (*p) {
    char_count += strlen(*p);
    ++p;
}

Note that strlen() will count spaces too.

If you don't want spaces or special characters counted, you could write your own length function such as:

int string_length (const char *str) {
    int len = 0;

    while(*str) {
        /* Count only lower-case letters a-z. */
        if (*str >= 'a' && *str <= 'z') ++len;
        ++str;
    }

    return len;
}

Assuming your array is called array ...

int count = 0, i;

for (i = 1; i <= 1000; ++i) {
    count += strlen(array[i]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM