strlen()与sizeof()
注意
- strlen()使用了**标准c语言库函数strlen()**来确定字符串长度头文件加入
#include<cstring>
- sizeof运算符指出整个数组的长度15字节,strlen()只计算可见的字符返回储存再数组中的字符串的长度
#include<iostream>
#include<cstring>
using namespace std;
int main(void)
{
const int size=15;
char name1[size];
char name2[size]="C++owboy";
cin>>name1;
cout<<name1<<endl;
cout<<"Well "<<name1<<" you name has ";
cout<<strlen(name1)<<" letters and is stored";
cout<<" in an array of is "<<sizeof(name1)<<" bytes\n";
name2[3]='\0'; //运送一个空字符过去
cout<<"Here are the first charcaters of my name: "<<name2<<endl;
}
程序运行结果
penglu
penglu
Well penglu you name has 6 letters and is stored in an array of is 15 bytes
Here are the first charcaters of my name: C++
程序说明
- 对于char数组类型字符串,如果cosmic是字符串,则数组的长度不得短语strlen(cosmic)+1
- c-风格字符串以‘\0’结尾,对于cout显示上述字符串,直到遇到空字符‘\0’停止
- 因此将name[3]设置为空字符,该字符串在第3个字符后即结束即使数组还有其他字符