Navigate back to the homepage

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

Vishnu Damwala
February 25th, 2020 · 1 min read

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.
1char proudToBeAnIndian[] = "East or West INDIA is best";
2strlen(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:

1#include <string.h>
2#include <stdio.h>
3
4int main()
5{
6 char country[] = "India", title[] = "MeshWorld";
7
8 printf("\n Length of title without null character: %zu", strlen(title));
9 printf("\n Length of title with null character: %zu", sizeof(title));
10
11 printf("\n Length of country without null character: %zu", strlen(country));
12 printf("\n Length of country with null character: %zu", sizeof(country));
13
14 return 0;
15}

Output:

1Length of title without null character: 9
2Length of title with null character: 10
3Length of country without null character: 5
4Length of country with null character: 6

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

More articles from MeshWorld

Convert hexadecimal color to rgb or rgba in php

Convert hexadecimal color to rgb or rgba in php

February 7th, 2020 · 1 min read

Get Array of IDs from Eloquent Collection in Laravel

Get an array of ids from Eloquent collection in Laravel using pluck() and modelKeys() function

January 2nd, 2020 · 1 min read
© 2017–2020 MeshWorld
Link to $https://twitter.com/meshworldindiaLink to $https://facebook.com/meshworldindiaLink to $https://instagram.com/meshworld.india/