字符串字面值的類型就是 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