C语言-字符串
字符
- 0,'0' ,‘\0’
#include
int main() {
char c = '0';
printf("%c\n", c); //0
printf("%d\n", c); //48
c = 0;
printf("%c\n", c); //
printf("%d\n", c); //0
c = '\0';
printf("%c\n", c); //
printf("%d\n", c); //0
return 0;
}
/*
0
48
0
0
*/
转义字符

计算字符串长度
#include
#include
int main() {
const char* p = "a\0\n\012ab0";
printf("%d\n", sizeof(p)); //4
printf("%d\n", sizeof("a\0\n\012ab0")); //8
//a \0 \n \012 a b 0 \0
int n = strlen(p);
printf("%d\n", n); //1
p++;
p++;
n = strlen(p);
printf("%d\n", n); //5
return 0;
}
字符数组和字符串常量的区别
#include
#include
using namespace std;
int main(){
const char *str1 = "abcde";//字符串常量
char str2[] = "abcde";//字符数组
cout << sizeof(str1) << endl;
cout << sizeof(str2) << endl;
cout << strlen(str1) << endl;
cout << strlen(str2) << endl;
return 0;
}
/*
4 //str1指针大小
6 //加上 '\0'
5 //不加 '\0'
5 //不加 '\0'
*/
字符串常量:字符串常量不能修改,因为是共用的,*str1因为是指针类型的字符串常量,所以只占4个字节。
字符数组:如果想将一个字符串存放到变量中,必须使用字符数组,就是用一个字符型数组存放一个字符串