用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 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短