The ones who are crazy enough to think they can change the world are the ones who do.
- Steve Jobs

strlen in C

Purpose of strlen()

strlen() is one of the inbuilt string function in c programming which is used to find the length of the given string.

How strlen() Works

The following diagram clearly illustrate the working principle of strlen() inbuilt string function in c.

strlen() in c

In the above diagram, strlen() will increment the count consecutively only when the next character is not '\0'.

Syntax - strlen()

  • strlen() accept only one string as a parameter
  • strlen() return a length of a string which is of integer type.
  • To use strlen() inbuilt string functions in C, we need to declare #include<string.h> header file.
Syntax
strlen(str1);

C Program - strlen()

Let us work through strlen() function, In the following program we will find the length of the string "ThisisStrlen" using strlen() inbuilt string function.

c-using-strlen.c
#include <stdio.h>
#include<string.h>
int main()
{
char str1[] = "ThisisStrlen";
printf("Length of str1 = %d ", strlen(str1));
return 0;
}
Length of str1 = 12

Note:

The above program prints the length of the string by excluding a null character at the end of the string.

C Program - Without strlen()

Let us count the length of the string without using inbuilt string function strlen().

c-without-strlen.c
#include <stdio.h>
#include<string.h>
int main()
{
char str1[] = "ThisisStrlen",i;
for(i=0; str1[i]!='\0';i++)
{
//	making using i to count str1 length
}
printf("Length of str1 = %d ",i);
return 0;
}
Length of str1 = 12

Note:

The above program looks verbose but yields same the result.

Did You Know?

When a string containing '\0' in its middle i.e) This\0willbreak, then strlen() will break and return the count upto '\0' i.e) it returns 4.

c-strlen-3.c
#include <stdio.h>
#include<string.h>
int main()
{
char str1[] = "This\0willbreak";
printf("Length of str1 = %d ", strlen(str1));
return 0;
}
Length of str1 = 4

Report Us

We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.

Report