用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 高考祝福语简短10字
15 送女士祝福语长辈简短
16 过节文案成语祝福语简短
17 父亲祝福语大全简短语
18 发小结婚简短祝福语