Advertisement



< Prev
Next >





C++ strlen() function




As evident from its name, strlen() is a function defined in the cstring header file, which gives us the total number of characters in a string, stored in a c-style char array.




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<iostream>
#include<cstring>

using namespace std;

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

cout<< "First string is : "<< str1 << "\n";
int length = strlen(str1);
cout<< "Length of first string is : " << length << "\n";


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

cout<< "Second string is : " << str2 << "\n";
length = strlen(str2);
cout<< "Length of second string is : " << 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<iostream>
#include<cstring>

using namespace std;

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


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

cout<< "The elements of the second string : " << str2 << "\n";
length = strlen(str2);
cout<< "Length of the second string is : " << 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