Related Tags

strlen
string
function
c language

# How to use the strlen() function in C

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 $10$ and $11$ are calculating the length of the two given strings (string1 and string2). Both strings were initialized at the beginning of the code on lines $6$ and $7$.

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

RELATED TAGS

strlen
string
function
c language