1. 字符串字面值
1.1 字符串字面值是一串常量字符,字符串字面值常量用双引号括起来的零个或多个字符表示。
"Hello World!" // simple string literal
"\nCC\toptions\tfile.[cC]\n" // string literal using newlines and tabs
"" // empty string literal
"a" // string with only one character.
'a' // not a string but a character
1.2 字符串字面值的连接:
cout << endl;
const char* str1 = "hello" " world";
cout << str1 << endl; // 输出:hello world
const char* str2 = "hello"
" world";
cout << str2 << endl; // 输出:hello world
const char* str3 = "hello \
world"; // 借用'\'的多行写法,
//注意引号间不能有多余的格式化字符
cout << str3 << endl; // 输出:hello world
//char* sp = "hello" + " world"; // 错误:没有这样的语法
//cout << "hello" + "world" << endl; // 错误:没有这样的语法
2. 赋值给变量
字符串字面值存储在文字常量区,实质是const char类型的数组,在程序运行过程中不能被改变。
2.1 字符串字面值可以赋值给char*类型的变量,但是与字符串字面值相关联的内存空间位于文字常量区,是只读的,因此它是常量字符数组。所以,为了尽早发现错误,应在变量类型的’*’号前加“const”。
cout << typeid("hello").name() << endl; // 输出: char const [6]
char* str1 = "hello";
cout << typeid(str1).name() << endl; // 输出: char *
//*str1 = 'a'; // 运行时出错:内存不能为“written”
cout << str1 << endl; // 输出:hello
const char* str2 = "hello";
cout << typeid(str2).name() << endl; // 输出:char const *
//*str2 = 'a'; // 编译时出错:不能给常量赋值
cout << str2 << endl; // 输出:hello
2.2 当将字符串直接量赋值给字符数组的初始值的时候。由于字符数组存放于栈中,因此编译器会将字符串直从文字常量区直接量复制到栈的数组内存中。因此,数组可以进行相应的修改。
char ch_arr[] = "hello";
cout << typeid(ch_arr).name() << endl; // 输出:char [6]
ch_arr[0] = 'a';
cout << ch_arr << endl; // 输出:aello
3. C风格字符串
3.1 为兼容C语言,C++中所有的字符串字面值都由编译器自动在末尾添加一个空字符,即’\0’,这就是C风格的字符串。
char ca1[] = {'h', 'e', 'l', 'l', 'o'}; // no null, not C-style string
char ca2[] = {'h', 'e', 'l', 'l', 'o', '\0'}; // explicit null
char ca3[]="hello"; // null terminator added automatically
const char *cp="hello"; // null terminator added automatically
cout << sizeof(ca1) << endl; // 输出:5
cout << sizeof(ca2) << endl; // 输出:6
cout << sizeof(ca3) << endl; // 输出:6,自动添加'\0'
cout << sizeof(cp) << endl; // 输出:4,为指针的存储空间
cout << sizeof("") << endl; // 输出:1,自动添加'\0'
cout << sizeof("\0") << endl; // 输出:2,自动添加'\0'
//char ca4[5] = "hello"; // 编译时出错:数组越界,数组长度应为6
3.2 C++语言通过(const) char *类型的指针来操纵C风格字符串。
const char *cp = "hello"; // 一个C风格字符串
while(*cp) // true表明是除null外的任意字符
{
// do something to *cp
++cp;
}
3.3 要使用C风格字符串的标准库函数,必须包含头文件,cstring是string.h头文件中的C++版本,而string.h是C语言提供的标准库。主要标准库函数有:
strlen(s); // 返回s的长度,不包括字符串结束符null
strcmp(s1, s2); // s1>s2,结果>0;s1=s2,结果=0;s1<s2,结果<0
strcat(s1, s2); // 将字符串s2连接到s1后,并返回s1
strcpy(s1, s2); // 将s2复制给s1,并返回s1
strncat(s1, s2, n); // 将s2的前n个字符连接到s1后面,并返回s1
strncpy(s1, s2, n); // 将s2的前n个字符复制给s1,并返回s1
if(cp1 < cp2) // compares address, not the values pointed to