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++)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With