Advertisement



< Prev
Next >





C strlen() function




As evident from its name, strlen() is string function defined in the string.h header file, which gives us the total number of characters in a string.




Signature of strlen() function


size_t strlen(const char *str);)






Note :








strlen() example


In the upcoming example, we have initialized two char array with different strings. Next, we are calling strlen() function on each of these String objects to determine their length.

/* Program to find the total length of a String using strlen() */

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

int main()
{
char str1[10]= "01234567"; 	/* First string */

printf("First String is %s",str1);
printf("\n");
int length = strlen(str1);
printf("Length of first String is %d", length);
printf("\n");


char str2[20]= "String Chapter";	/* Second string */

printf("Second String is %s",str2);
printf("\n");
length = strlen(str2);
printf("Length of second String is %d", length);

return 0;
}


Output is :


First String is 01234567
Length of first String is 8
Second String is String Chapter
Length of second String is 14


Program Analysis





Advertisement




Finding length of an empty string using strlen()


In the upcoming example, we have finding length of an empty string, which is created but not initialized with any value.
/* Program to find the length of an empty string*/


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

int main()
{
char str1[10] = ""; /* An empty string */
 
printf("The elements of the first string : ", str1);
printf("\n");
int length = strlen(str1);
printf("Length of the first string is : %d ", length);
printf("\n");


/*Another way to create a string */
char str2[] = {'A'}; /* Not an empty string */

printf("The elements of the second string : %s ", str2);
printf("\n");
length = strlen(str2);
printf("Length of the second tring is : %d ",length);

return 0;
}


Output is :


The elements of the first string :
Length of the first string is : 0
The elements of the second string : A
Length of the second tring is : 1


Program Analysis





Please share this article -




< Prev
Next >
< C strchr() function
C strupr() function >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement