#include<iostream>
using namespace std;
int stringLength(char* p);
int main() {
//char str2[9] = "123456789";
//定义为str[9]报:C++ a value of type cannot be used to initialize an entity of type"char(9)"
//因为无法吧'\0'自动加入到字符串结尾
char str1[] = "123456789";//字符串数组
cout << "str1[]:" << str1 << endl;
cout << "sizeof(str1):" << sizeof(str1) << endl;
cout << "strlen(str1):" << strlen(str1) << endl;
for (int i = 0; i < 10; i++)
{
cout << int(str1[i]) << " ";
}
cout << endl;
/*
str1[]:123456789
sizeof(str1):10
strlen(str1):9
49 50 51 52 53 54 55 56 57 0
*/
char str2[15] = "123456789";
cout << "str2[15]:" << str2 << endl;
cout << "sizeof(str2):" << sizeof(str2) << endl;
cout << "strlen(str2):" << strlen(str2) << endl;
for (int i = 0; i < 15; i++)
{
cout << int(str2[i]) << " ";
}
cout << endl;
/*
str2[15]:123456789
sizeof(str2):15
strlen(str2):9
49 50 51 52 53 54 55 56 57 0 0 0 0 0 0//发现没有使用的空间都是'\0'填充
*/
//总结:
//sizeof()统计这个字符串数组占用的空间字节数
//srtlen()只统计有意义字符的个数,不包括'\0'
char str3[9] = { '1','2','3','4','5','6','7','8','9' };//字符数组
cout << "str3[15]:" << str3 << endl;
cout << "sizeof(str3):" << sizeof(str3) << endl;
cout << "strlen(str3):" << strlen(str3) << endl;
for (int i = 0; i < 9; i++)
{
cout << int(str3[i]) << " ";
}
cout << endl;
/*总结:
str3[15]:123456789烫烫烫烫烫?
sizeof(str3):9
strlen(str3):21
49 50 51 52 53 54 55 56 57
发现输出不对,strlen也不对,可以判断strlen是找'\0',判断字符长度,我把str[4]='\0'后,strlen(str3):3
所以想用cout输出整个字符,字符结尾必须加上'\0'
*/
char str4[15] = { '1','2','3','4','5','6','7','8','9' };//字符数组
cout << "str4[15]:" << str4 << endl;
cout << "sizeof(str4):" << sizeof(str4) << endl;
cout << "strlen(str4):" << strlen(str4) << endl;
for (int i = 0; i < 15; i++)
{
cout << int(str4[i])<<" ";
}
cout << endl;
/*
str2[15]:123456789
sizeof(str4):15
strlen(str4):9
49 50 51 52 53 54 55 56 57 0 0 0 0 0 0//可以看出数字空着的空间全部用'\0'填充
*/
return 0;
}
int stringLength(char* p) {
int i = 0;
while (*(p+i) != '\0') {
i = i + 1;
}
return i;
}