C++ 程序查找字符串长度
字符串是一维字符数组,以空字符结尾。字符串的长度是在空字符之前的字符数。
例如。
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
广告