strlen function in C Programming

4 years, 6 months ago C Programming

strlen function is a very simple string library function defined in string.h header file. It returns the length of a given byte string. Here length means how many characters are containing in that string. But it’s noted that the null character will always be excluded from the length. Its basic form is given below:

strlen(string);

Here ‘string’ is the parameter of this function. This function returns an integer which indicates the length of string. Please consider the following example:

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

int main()
{
 int x;
 char str1[] = "Bangladesh";
 char str2[] = "Bangla";
 x = strlen(str1);
 printf("%d\n", x);
 x = strlen(str2);
 printf("%d\n", x);
 return 0;
}

Output:

10

6

You can write the above program like below:

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

int main()
{
 char str1[] = "Bangladesh";
 char str2[] = "Bangla";
 printf("%d\n", strlen(str1));
 printf("%d\n", strlen(str2));
 return 0;
}

Output:

10

6

If you want to get the length with null character, you have to use the sizeof() function. Please consider the following program:

#include <stdio.h>

int main()
{
 char str1[] = "Bangladesh";
 char str2[] = "Bangla";
 printf("%d\n", sizeof(str1));
 printf("%d\n", sizeof(str2));
 return 0;
}

Output:

11

7

That’s all about strlen function. If you have any question, just shout in the comment box given below. Happy Coding!!!

Previous Next
Comments
Have you read the comment guideline?

Give me useful, constructive criticism. Spot a typo or an error? Let me know and I will correct it.