用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
热门推荐
10 同事换单位简短祝福语
11 谢谢朋友的祝福语简短
12 立秋节气简短祝福语
13 新房祝福语简短10字
14 长辈新年祝福语大全简短
15 新年给大家简短祝福语
16 生日祝福语简短独特姑姑
17 芭比的婚礼祝福语简短
18 邀请新人祝福语简短英文