What is strlen function in C language?


The C library function size_t strlen(const char *str) computes the length of the string str up to, but not including the terminating null character.

An array of characters is called a string.

Declaration

Given below is the declaration of an array −

char stringname [size];

For example − char a[50]; string of length 50 characters

Initialization

  • Using single character constant −
char a[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
  • Using string constants −
char a[10] = "Hello":;

Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’

The strlen ( ) function

This function gives the length of the string, i.e., the number of characters in a string.

Syntax

The syntax of strlen() function is as follows −

int strlen (string name)

Sample program

The following program shows the usage of strlen() function.

 Live Demo

#include <string.h>
main ( ){
   char a[30] = "Hello";
   int l;
   l = strlen (a);
   printf ("length of the string = %d", l);
   getch ( );
}

Output

When the above program is executed, it produces the following result −

length of the string = 5
Note : "\0" not counted as a character.

Consider another example.

Example

Following is the C program to find the length of a string −

 Live Demo

#include<stdio.h>
#include<string.h>
int main(){
   int str1, str2;
   //initializing the strings
   char string1[] = "Welcome To";
   char string2[] = {'T','U','T','O','R','I','A','L','\0'};
   //calculating the length of the two strings
   str1 = strlen(string1);
   str2 = strlen(string2);
   printf("string1 length is: %d 
", str1);    printf("string2 length is: %d
", str2); }

Output

When the above program is executed, it produces the following result −

string1 length is: 10
string2 length is: 8

Updated on: 17-Mar-2021

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements