
如果字符串中没有空字符,该函数的行为是未定义的。在本教程中,我们将通过实例来了解C++ strlen()函数。
C++ strlen
C++ strlen()是一个内置函数,用于计算字符串的长度。strlen()方法返回给定的C语言字符串的长度,它被定义在string.h 头文件下。 strlen()将一个空尾的字节字符串 str作为其参数,并返回其长度。该长度不包括空字符。
语法
int strlen(const char *str_var);
这里str_var是字符串变量,我们必须找到它的长度。
参数
它需要一个参数,一个指向以空结束的字节字符串的指针。空字符是字符串的终点。如果一个空字符没有终止,则行为未定。
返回值
它返回一个整数,给出所传递字符串的长度。
关于strlen()函数的程序示例
例1:写一个程序来展示strlen()函数的机制。
#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;
}
输出
String: hello world
Length: 11
String: I am the best
Length: 14
String: a
Length: 1
String: 123
Length: 3
例2:取两个输入字符串,用strlen()函数检查这两个字符串的长度是否相等。
请看下面的代码。
#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";
}
}
输出
Length of both the strings are not equal
本教程到此结束。