Reputation: 178
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?
Upvotes: 1
Views: 7235
Reputation: 2607
Assuming your array is called array
...
int count = 0, i;
for (i = 1; i <= 1000; ++i) {
count += strlen(array[i]);
}
Upvotes: 2
Reputation: 141
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;
}
Upvotes: 6