C++ 提供了以下兩種類型的字符串表示形式:
C 風格字符串C 風格的字符串起源于 C 語言,并在 C++ 中繼續得到支持。字符串實際上是使用 null 字符 '\0' 終止的一維字符數組。因此,一個以 null 結尾的字符串,包含了組成字符串的字符。 下面的聲明和初始化創建了一個 "Hello" 字符串。由于在數組的末尾存儲了空字符,所以字符數組的大小比單詞 "Hello" 的字符數多一個。 char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; 依據數組初始化規則,您可以把上面的語句寫成以下語句: char greeting[] = "Hello"; 以下是 C/C++ 中定義的字符串的內存表示: ![]() 其實,您不需要把 null 字符放在字符串常量的末尾。C++ 編譯器會在初始化數組時,自動把 '\0' 放在字符串的末尾。讓我們嘗試輸出上面的字符串: #include <iostream> using namespace std; int main () { char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; cout << "Greeting message: "; cout << greeting << endl; return 0; } 當上面的代碼被編譯和執行時,它會產生下列結果: Greeting message: Hello C++ 中有大量的函數用來操作以 null 結尾的字符串:supports a wide range of functions that manipulate null-terminated strings:
下面的實例使用了上述的一些函數: #include <iostream> #include <cstring> using namespace std; int main () { char str1[10] = "Hello"; char str2[10] = "World"; char str3[10]; int len ; // 復制 str1 到 str3 strcpy( str3, str1); cout << "strcpy( str3, str1) : " << str3 << endl; // 連接 str1 和 str2 strcat( str1, str2); cout << "strcat( str1, str2): " << str1 << endl; // 連接后,str1 的總長度 len = strlen(str1); cout << "strlen(str1) : " << len << endl; return 0; } 當上面的代碼被編譯和執行時,它會產生下列結果: strcpy( str3, str1) : Hello strcat( str1, str2): HelloWorld strlen(str1) : 10 C++ 中的 String 類C++ 標準庫提供了 string 類類型,支持上述所有的操作,另外還增加了其他更多的功能。我們將學習 C++ 標準庫中的這個類,現在讓我們先來看看下面這個實例: 現在您可能還無法透徹地理解這個實例,因為到目前為止我們還沒有討論類和對象。所以現在您可以只是粗略地看下這個實例,等理解了面向對象的概念之后再回頭來理解這個實例。 #include <iostream> #include <string> using namespace std; int main () { string str1 = "Hello"; string str2 = "World"; string str3; int len ; // 復制 str1 到 str3 str3 = str1; cout << "str3 : " << str3 << endl; // 連接 str1 和 str2 str3 = str1 + str2; cout << "str1 + str2 : " << str3 << endl; // 連接后,str3 的總長度 len = str3.size(); cout << "str3.size() : " << len << endl; return 0; } 當上面的代碼被編譯和執行時,它會產生下列結果: str3 : Hello str1 + str2 : HelloWorld str3.size() : 10 |