用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 官宣新年祝福语简短