C library function - strlen()



The C library strlen() function is used to calculates the length of the string. This function doesn't count the null character '\0'.

In this function, we pass the pointer to the first character of the string whose length we want to determine and as a result it returns the length of the string.

Syntax

Following is the syntax of the C library strlen() function −

size_t strlen(const char *str)

Parameters

This function accepts only a single parameter −

  • str − This is the string whose length is to be found.

Return Value

This function returns the length of the string.

Example 1

Following is the C library program that illustrate the given string to find the length using strlen() function.

#include <stdio.h>
#include <string.h>

int main() {
   char len[] = "Tutorialspoint";
   printf("The length of given string = %d", strlen(len));
   return 0;
}

Output

On execution of above code, we get the following result −

The length of given string = 14

Example 2

Here, we are using two functions − strcpy() which create the first string by copying the second parameter. Then we calculate the length of string with the help of strlen().

#include <stdio.h>
#include >string.h>

int main () {
   char str[50];
   int len;
   strcpy(str, "This is tutorialspoint");
   len = strlen(str);
   printf("Length of |%s| is |%d|\n", str, len);
   return(0);
}

Output

After executing the code, we get the following result −

Length of |This is tutorialspoint| is |22|

Example 3

Below the example demonstrate the strlen() function in loop iteration to get the count of given specified character.

#include<stdio.h>
#include<string.h>
int main()
{
   int i, cnt;
   char x[] = "Welcome to Hello World";
   cnt = 0;
   for(i = 0; i < strlen(x); i++)
   {
   if(x[i] == 'e')
   cnt++;
   }
printf("The number of e's in %s is %d\n", x, cnt);
return 0;
}

Output

The above code produces the following result −

The number of e's in Welcome to Hello World is 3
Advertisements