Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C language, how find the length of a word in a 2d array?

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?

like image 505
Alex Avatar asked Apr 04 '13 17:04

Alex


2 Answers

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 */
}
like image 199
NPE Avatar answered Sep 30 '22 00:09

NPE


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++)
like image 34
Jonathan Leffler Avatar answered Sep 29 '22 23:09

Jonathan Leffler