How to use the strlen() function in C

Share

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.

Syntax

The following is the syntax of the strlen() function:

Syntax

Let's see some examples to use the strlen() method in C.

Example 1

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);
}

Explanation

  • The 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.

Example 2

We see how strlen() works with the null character:

Code

#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);
}

Explanation

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.

Copyright ©2024 Educative, Inc. All rights reserved