C - Get the string length with while loop

Introduction

The following code will initialize two strings and then find out how many characters there are in each, excluding the null character:

Demo

#include <stdio.h>
int main(void)
{
  char str1[] = "To be or not to be";
  char str2[] = ",that is the question";
  unsigned int count = 0;                // Stores the string length
  while (str1[count] != '\0')            // Increment count till we reach the
    ++count;                             // terminating character.

  printf("The length of the string \"%s\" is %d characters.\n", str1, count);

  count = 0;                             // Reset count for next string
  while (str2[count] != '\0')            // Count characters in second string
    ++count;// www  .j  a v  a2  s. co  m

  printf("The length of the string \"%s\" is %d characters.\n", str2, count);
  return 0;
}

Result

We used a while loop that determines the length of the first string:

while (str1[count] != '\0')              // Increment count till we reach the
   ++count;                                 // terminating character.

We use count to step through the elements in the str1 array.

To find the length of str1, you increment count in the while loop as long as you haven't reached the null character that marks the end of the string.

The while loop condition compares the value of the str1[count] element with '\0'. however, this loop would often be written like this:

while(str1[count])
  ++count;

The ASCII code value for the  '\0' character is zero, which corresponds to the Boolean value false. 

All other ASCII code values are nonzero and therefore correspond to the Boolean value true. 

Thus this version of the loop continues as long as str1[count] is not '\0', which is the same as the previous version.

Related Example