سؤال

I am trying to make a condition for a for loop where i have to say (c<wordlength) but im not sure how to find the length of the word.

so lets say i have an arrary called...

char shopping[10][10]={"BAGELS","HAM","EGGS"};

what is the right syntax to find that shopping[0] has 6 letters?

هل كانت مفيدة؟

المحلول

The right syntax is

strlen(shopping[0])

This returns a value of type size_t that does not include the NUL terminator.

See man strlen for details.

If you are using strlen(unchanging_string) as the terminal condition of a loop, it is prudent to call it once before the loop instead of calling it on every iteration.

An alternative way to loop over the characters of shopping[0] is as follows:

char *s = shopping[0];
while (*s) {
  /* (*s) is the current character */
}

نصائح أخرى

size_t len = strlen(shopping[0]);

Note, though, that you should not write:

for (size_t i = 0; i < strlen(shopping[0]); i++)

This can lead to bad performance on long strings. Use:

size_t len = strlen(shopping[0]);
for (size_t i = 0; i < len; i++)

Actually shopping[0] has 7 chars one you forgot \0 char that is for string termination. Although strlen() give you length of string, that number of char before \0.

strlen(shopping[0])

But Total char are strlen(shopping[0]) + 1 = 7

In memory your shopping[0] is something like:

+----+----+----+---+---+----+----+----+---+---+ 
| 'B'| 'A' |'G'|'E'|'L'| 'S'|'\0'| 0  | 0 |   |
+----+----+----+---+---+----+----+----+---+---+
                              ^ `\0` also a char in shopping[0]

Edit:

As I read your question again you says 6 letters So strlen(shopping[0] ) is your answer give you 6.

Because you wants a loop to find number of letters (char in my answer non '\0') then calling strlen() is useless. I would like that you should take benefit of null termination string in C:

int num=0;
for(num = 0; shopping[0][num]!='\0'; num++);
printf("\n  number of letters are %d\n",num);

I think other answers are not good, they are using strlen() unnecessary. If I am missing something, Please let me know

You can write the code using a for loop to find the size of each element in the shopping array:

for(i =0;i<10;i++)
{
    j=0;
    while(shopping[i][j])
    {
        j++;
    }
}

where j will return the size of each shopping array element.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top