C++ 字串
C++ 字串
C++ 提供了以下兩種型別的字串表示形式:
- C 風格字串
- C++ 引入的 string 類型別
C 風格字串
C 風格的字串起源於 C 語言,並在 C++ 中繼續得到支援。字串實際上是使用 null 字元 \0 終止的一維字元陣列。因此,一個以 null 結尾的字串,包含了組成字串的字元。
下面的宣告和初始化建立了一個 itread01 字串。由於在陣列的末尾儲存了空字元,所以字元陣列的大小比單詞 itread01 的字元數多一個。
char site[7] = {'R', 'U', 'N', 'O', 'O', 'B', '\0'};
依據陣列初始化規則,您可以把上面的語句寫成以下語句:
char site[] = "itread01";
以下是 C/C++ 中定義的字串的記憶體表示:

其實,您不需要把 null 字元放在字串常量的末尾。C++ 編譯器會在初始化陣列時,自動把 \0 放在字串的末尾。讓我們嘗試輸出上面的字串:
例項
#include <iostream>
using namespace std;
int main ()
{
char site[7] = {'R', 'U', 'N', 'O', 'O', 'B', '\0'};
cout << "入門教學: ";
cout << site << endl;
return 0;
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
入門教學: itread01
C++ 中有大量的函式用來操作以 null 結尾的字串:
序號 | 函式 & 目的 |
---|---|
1 | strcpy(s1, s2); 複製字串 s2 到字串 s1。 |
2 | strcat(s1, s2); 連線字串 s2 到字串 s1 的末尾。連線字串也可以用 + 號,例如: string str1 = "itread01"; string str2 = "google"; string str = str1 + str2; |
3 | strlen(s1); 返回字串 s1 的長度。 |
4 | strcmp(s1, s2); 如果 s1 和 s2 是相同的,則返回 0;如果 s1<s2 則返回值小於 0;如果 s1>s2 則返回值大於 0。 |
5 | strchr(s1, ch); 返回一個指標,指向字串 s1 中字元 ch 的第一次出現的位置。 |
6 | strstr(s1, s2); 返回一個指標,指向字串 s1 中字串 s2 的第一次出現的位置。 |
下面的例項使用了上述的一些函式:
例項
#include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char str1[13] = "itread01";
char str2[13] = "google";
char str3[13];
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) : itread01 strcat( str1, str2): itread01google strlen(str1) : 12
C++ 中的 String 類
C++ 標準庫提供了 string 類型別,支援上述所有的操作,另外還增加了其他更多的功能。我們將學習 C++ 標準庫中的這個類,現在讓我們先來看看下面這個例項:
現在您可能還無法透徹地理解這個例項,因為到目前為止我們還沒有討論類和物件。所以現在您可以只是粗略地看下這個例項,等理解了面向物件的概念之後再回頭來理解這個例項。
例項
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str1 = "itread01";
string str2 = "google";
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 : itread01 str1 + str2 : itread01google str3.size() : 12