字符串是一维字符数组,以空字符结尾。字符串的长度是字符串中空字符之前的字符数。
例如。
char str[] = “The sky is blue”; Number of characters in the above string = 15
查找字符串长度的程序如下所示。
#include<iostream> using namespace std; int main() { char str[] = "Apple"; int count = 0; while (str[count] != '\0') count++; cout<<"The string is "<<str<<endl; cout <<"The length of the string is "<<count<<endl; return 0; }
输出结果
The string is Apple The length of the string is 5
在上面的程序中,count变量在while循环中递增,直到在字符串中到达空字符为止。最后,count变量保存字符串的长度。给出如下。
while (str[count] != '\0') count++;
获得字符串的长度后,它会显示在屏幕上。下面的代码片段对此进行了演示。
cout<<"The string is "<<str<<endl; cout<<"The length of the string is "<<count<<endl;
字符串的长度也可以通过使用该strlen()
函数找到。下面的程序对此进行了演示。
#include<iostream> #include<string.h> using namespace std; int main() { char str[] = "Grapes are green"; int count = 0; cout<<"The string is "<<str<<endl; cout <<"The length of the string is "<<strlen(str); return 0; }
输出结果
The string is Grapes are green The length of the string is 16