#include <stdio.h>
#include <string.h>
/*c语言没有字符串类型,通过字符数组模拟
c语言字符串以字符'\0'结尾*/
int main() {
//不指定长度,没有'\0'结束符. 有多少个元素就有多长
char buf[] = {'a', 'b', 'c'};
printf("buf = %s\n", buf); //buf = abc�]�
//指定长度,后面没有元素,自读补0
char buf1[100] = {'a', 'b', 'c'};
printf("buf1 = %s\n", buf1); //buf1 = abc
// 所有元素赋值为0
char buf2[100] = {0};
//字符0有对应的assic码
char buf3[100] = {'a', 'b', 'c', '0', '6'};
printf("buf3 = %s\n", buf3);//buf3 = abc06
//数字0和\0等价,表示字符串结束
char buf4[100] = {'a', 'b', 'c', 0, '6'};
printf("buf4 = %s\n", buf4);//buf4 = abc
char buf5[100] = {'a', 'b', 'c', '\0', '6'};
printf("buf5 = %s\n", buf5); //buf5 = abc
//通常直接使用字符串初始化
char buf6[] = "hello world!!!";
// strlen测试字符串长度,不包括\0, sizeof测试数组长度,包含\0
printf("strlen = %d sizeof = %d\n", strlen(buf6), sizeof(buf6)); //strlen = 14 sizeof = 15
char buf7[100] = "hello world!!!";
printf("strlen = %d sizeof = %d\n", strlen(buf7), sizeof(buf7)); //strlen = 14 sizeof = 100
return 0;
}
网友评论