C++ strlen() is a built-in function used to calculate the length of the string. The method returns the length of the given C-string and is defined under the string.h header file. The strlen() takes a null-terminated byte string str as its argument and returns its length. The length does not include a null character.
Syntax
int strlen(const char *str_var);
Here, str_var is the string variable we have to find the length.
Parameters
It takes one parameter, a pointer that points to the null-terminated byte string. A null character terminates the string. If a null character does not terminate it, the behavior is undefined.
Return Value
It returns an integer giving the length of the passed string.
Example 1
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char k[] = "hello world";
char m[] = "I am the best\n";
char n[] = "a";
char o[] = "123";
int f, i, g, h;
f = strlen(k);
i = strlen(m);
g = strlen(n);
h = strlen(o);
cout << "String: " << k << endl;
cout << "Length: " << strlen(k) << endl;
cout << "String: " << m << endl;
cout << "Length: " << strlen(m) << endl;
cout << "String: " << n << endl;
cout << "Length: " << strlen(n) << endl;
cout << "String: " << o << endl;
cout << "Length: " << strlen(o) << endl;
}
Output
String: hello world
Length: 11
String: I am the best
Length: 14
String: a
Length: 1
String: 123
Length: 3
Example 2
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char a[] = "Hello I am a geek!";
char b[] = "I love AppDividend!";
if (strlen(a) == strlen(b))
{
cout << "Length of both the strings are equal";
}
else
{
cout << "Length of the both the strings are not equal";
}
}
Output
Length of both the strings are not equal
That’s it for this tutorial.