The strlen()
function in C++ returns the length of the given C-string. It is defined in the cstring header file.
Example
#include <iostream>
#include <cstring>
using namespace std;
int main() {
// initialize C-string
char song[] = "We Will Rock You!";
// print the length of the song string
cout << strlen(song);
return 0;
}
// Output: 17
strlen() Syntax
The syntax of the strlen()
function is:
strlen(const char* str);
Here, str is the string whose length we need to find out, which is casted to a const char*
.
strlen() Parameters
The strlen()
function takes the following parameter:
- str - pointer to the C-string (null-terminated string) whose length is to be calculated
strlen() Return Value
The strlen()
function returns:
- the length of the C-string (
size_t
)
strlen() Prototype
The prototype of strlen()
as defined in the cstring header file is:
size_t strlen(const char* str);
Note: The returned length does not include the null character '\0'
.
strlen() Undefined Behavior
The behavior of strlen()
is undefined if:
- there is no null character
'\0'
in the string i.e. if it is not a C-string
Example: C++ strlen()
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char str1[] = "This a string";
char str2[] = "This is another string";
// find lengths of str1 and str2
// size_t return value converted to int
int len1 = strlen(str1);
int len2 = strlen(str2);
cout << "Length of str1 = " << len1 << endl;
cout << "Length of str2 = " << len2 << endl;
if (len1 > len2)
cout << "str1 is longer than str2";
else if (len1 < len2)
cout << "str2 is longer than str1";
else
cout << "str1 and str2 are of equal length";
return 0;
}
Output
Length of str1 = 13 Length of str2 = 22 str2 is longer than str1