简体   繁体   English

C-计算字符串数组中的字符数

[英]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: 我一直在研究一个程序,以完成Project Euler的问题17,我尝试用C来完成。问题:

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. 如果数字1到5用单词写出来:1、2、3、4、5,则总共使用3 + 3 + 5 + 4 + 4 = 19个字母。

If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? 如果用文字写出从1到1000(含1000)之间的所有数字,那么将使用多少个字母?

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). 我编写了一个函数,该函数将1到1000之间的所有数字以单词形式放入具有1001个元素的数组中(对于迭代,最后一个为NULL)。 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. 请注意, strlen()也将计算空格。

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 ... 假设您的数组称为array ...

int count = 0, i;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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