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 proudToBeAnIndian[] = "East or West INDIA is best";
strlen(proudToBeAnIndian);
  • 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 country[] = "India", title[] = "MeshWorld";

    printf("\n Length of title without null character: %zu", strlen(title));
    printf("\n Length of title with null character: %zu", sizeof(title));

    printf("\n Length of country without null character: %zu", strlen(country));
    printf("\n Length of country with null character: %zu", sizeof(country));

    return 0;
}

Output

Length of title without null character: 9
Length of title with null character: 10
Length of country without null character: 5
Length of country with null character: 6

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

Avatar

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳

Next
Previous

Related