The strlen()
function in C is used to calculate the length of a string.
Note:
strlen()
calculates the length of a string up to, but not including, the terminating null character.
Return Value: The function returns the length of the string passed to it.
The following is the syntax of the strlen()
function:
Let's see some examples to use the strlen()
method in C.
The following example takes a simple string string1
and calculates its length.
#include<stdio.h>#include<string.h>int main() {int len1;char string1[] = "Hello World!";len1 = strlen(string1);printf("Length of string1 is: %d \n", len1);}
strlen()
function from the string.h library is used to calculate the length of the string stored in string1
. This length is then assigned to the variable len1
.We see how strlen()
works with the null character:
#include<stdio.h>#include<string.h>int main() {int len2;char string2[] = {'c','o','m','p','u','t','e','r','\0'};len2 = strlen(string2);printf("Length of string2 is: %d \n", len2);}
In the output displayed on the console, that the length of string2
is 888 instead of 999. This is because strlen()
does not count the null character (\0
) while counting.
Free Resources