字符串字面值的类型就是 const char 类型的数组。C++ 从 C 语言继承下来的一种通用结构是C 风格字符串,而字符串字面值就是该类型的实例。实际上,C 风格字符串既不能确切地归结为 C 语言的类型,也不能归结为 C++ 语言的类型,而是以空字符 null 结束的字符数组:
char ca1[] = {'C', '+', '+'}; // no null, not C-style string char ca2[] = {'C', '+', '+', '\0'}; // explicit null char ca3[] = "C++"; // null terminator added automatically const char *cp = "C++"; // null terminator added automatically char *cp1 = ca1; // points to first element of a array, but not C-style string char *cp2 = ca2; // points to first element of a null-terminated char array
ca1 和 cp1 都不是 C 风格字符串:ca1 是一个不带结束符 null 的字符数组,而指针 cp1 指向 ca1,因此,它指向的并不是以 null 结束的数组。其他的声明则都是 C 风格字符串,数组的名字即是指向该数组第一个元素的指针。于是,ca2 和ca3 分别是指向各自数组第一个元素的指针。
C 风格字符串的标准库函数
cstring 是 string.h 头文件的 C++ 版本,而 string.h 则是 C 语言提供的标准库。
表 4.1. 操纵 C 风格字符串的标准库函数
strlen(s) | Returns the length of s, not counting the null. 返回 s 的长度,不包括字符串结束符 null |
strcmp(s1, s2) | Compares s1 and s2 for equality. Returns 0 ifs1 == s2, positive value if s1 > s2, negative value if s1 < s2. 比较两个字符串 s1 和 s2 是否相同。若 s1 与 s2 相等,返回 0;若s1 大于 s2,返回正数;若 s1 小于 s2,则返回负数 |
strcat(s1, s2) | Appends s2 to s1. Returns s1. 将字符串 s2 连接到 s1 后,并返回 s1 |
strcpy(s1, s2) | Copies s2 into s1. Returns s1. 将 s2 复制给 s1,并返回 s1 |
strncat(s1, s2,n) | Appends n characters from s2 onto s1. Returnss1. 将 s2 的前 n 个字符连接到 s1 后面,并返回 s1 |
strncpy(s1, s2, n) | Copies n characters from s2 into s1. Returnss1. 将 s2 的前 n 个字符复制给 s1,并返回 s1 |
#include <cstring>
注意:
1.永远不要忘记字符串结束符 null