DEV Community

Cover image for How to find the length of a string using strlen in C
Vishnu Damwala
Vishnu Damwala

Posted on • Originally published at meshworld.in

How to find the length of a string using strlen in C

A tutorial for finding the length of a string using strlen in C - language

  • The strlen() function counts the number of characters in a given string and returns the long unsigned integer value.
  • It is defined in C standard library, within <string.h> header file.
char saying[] = "Better late than never";
strlen(saying);
Enter fullscreen mode Exit fullscreen mode
  • It stops counting when the null character is encounter. Because in C, null character is considered as the end of the string.

Working example

#include <string.h>
#include <stdio.h>

int main()
{
    char planet[] = "Earth";

    printf("\n Using strlen for planet without null character: %zu", strlen(planet));
    printf("\n Using sizeof for planet with null character: %zu", sizeof(planet));

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output

Using strlen for planet without null character: 5
Using sizeof for planet with null character: 6
Enter fullscreen mode Exit fullscreen mode

Note that the strlen() function doesn't count for the null character \0 whereas sizeof() function does.

Read the complete post on our site Find the length of a string using strlen() in C

Read others post on our site MeshWorld

Happy 😄 coding

With ❤️ from 🇮🇳

Top comments (0)