Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

strlen
string
function
c language

How to use the strlen() function in C

Educative Answers Team

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:

Implementation

The following example implements the strlen() function in C.

int main() {
  
  int len1, len2;
  
  //initializing the strings
  char string1[] = "Hello";
  char string2[] = {'c','o','m','p','u','t','e','r','\0'};
  
  //calculating the length of the two strings
  len1 = strlen(string1);
  len2 = strlen(string2);
  
  //displaying the values
  printf("Length of string1 is: %d \n", len1);
  printf("Length of string2 is: %d \n", len2);
}

Understanding the code

In the code above, lines 1010 and 1111 are calculating the length of the two given strings (string1 and string2). Both strings were initialized at the beginning of the code on lines 66 and 77.

You might have noticed, in the output displayed on the console, that the length of string2 is 88 instead of 99. This is because strlen() does not count the null character (\0) while counting.

RELATED TAGS

strlen
string
function
c language
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring