C++ 笔记(09)— 字符串(C 风格字符串、C++字符串 string)
C++ 提供了以下兩種類型的字符串表示形式:
C風格字符串;C++引入的string類類型;
1. C 風格字符串
C 風格的字符串起源于 C 語言,并在 C++ 中繼續得到支持。字符串實際上是使用 null 字符 \0 終止的一維字符數組。因此,一個以 null 結尾的字符串,包含了組成字符串的字符。
下面的聲明和初始化創建了一個 “Hello” 字符串。由于在數組的末尾存儲了空字符,所以字符數組的大小比單詞 “Hello” 的字符數多一個。
char a[6]={'H', 'e', 'l', 'l', 'o', '\0'};
依據數組初始化規則,可以把上面的語句寫成以下語句:
char a[] = "hello"
請注意,該數組的最后一個字符為空字符 \0 。這也被稱為字符串結束字符,因為它告訴編譯器,字符串到此結束。這種 C 風格字符串是特殊的字符數組,因為總是在最后一個字符后加上空字符 \0 。
在代碼中使用字符串字面量時,編譯器將負責在它后面添加 \0 。在數組中間插入 \0 并不會改變數組的長度,而只會導致將該數組作為輸入的字符串處理將到這個位置結束。
其實,不需要把 null 字符放在字符串常量的末尾。 C++ 編譯器會在初始化數組時,自動把 \0 放在字符串的末尾。讓我們嘗試輸出上面的字符串:
#include <iostream>
using namespace std;int main()
{ char a[] = {'h','e', 'l', 'l', 'o'}; // 'h' 不能是雙引號cout << "sizeof(a) is " << sizeof(a) << " a is " << a << endl;char b[] = {'h','e', 'l', 'l', 'o', '\0'};cout << "sizeof(b) is " << sizeof(b) << " b is " << b << endl;char c[] = {'h','e', '\0', 'l', 'o', '\0'};cout << "sizeof(c) is " << sizeof(c) << " c is " << c << endl;return 0;
}
輸出:
sizeof(a) is 5 a is hello
sizeof(b) is 6 b is hello
sizeof(c) is 6 c is he
使用 C 語言編寫的應用程序經常使用 strcpy() 等字符串復制函數、 strcat() 等拼接函數,還經常使用 strlen() 來確定字符串的長度。
這些 C 風格字符串作為輸入的函數非常危險,因為它們尋找終止空字符,如果程序員沒有在字符數組末尾添加空字符,這些函數將跨越字符數組的邊界。
2. C++ 風格字符串
C++ 標準庫提供了 string 類類型,支持上述所有的操作,另外還增加了其他更多的功能。無論是處理文本輸入,還是執行拼接等字符串操作,使用 C++ 標準字符串都是更高效、更安全的方式。
不同于字符數組(C 風格字符串實現), std::string 是動態的,在需要存儲更多數據時其容量將增大。
要使用 C++ 字符串,需要包含頭文件 string :
#include <string>
使用示例:
#include <iostream>
#include <string>using namespace std;int main()
{ string a = "hello";string b = "world";string dst = "";int len = 0;dst = a;cout << "dst:" << dst << endl;dst = a + b;cout << "dst:" << dst << endl;len = dst.size();cout << "dst.size :" << len << endl;cout << "dst.length:" << dst.length() << endl;cout << "dst.append(11):" << dst.append("11") << endl;cout << "dst.find('e'):" << dst.find('e') << endl;dst.replace(2, 3, "Z"); // //從位置 2 開始,之后的 3 個字符替換為 "Z",cout << "dst.replace('e', 'Z')" << dst << endl;int first = dst.find_first_of("o");int last = dst.find_last_of("d");cout << "first is " << first << endl;cout << "last is " << last << endl;return 0;
}
輸出結果:
dst:hello
dst:helloworld
dst.size :10
dst.length:10
dst.append(11):helloworld11
dst.find('e'):1
dst.replace('e', 'Z')heZworld11
first is 4
last is 7
總結
以上是生活随笔為你收集整理的C++ 笔记(09)— 字符串(C 风格字符串、C++字符串 string)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 东风已到下一句是什么呢?
- 下一篇: 2022-2028年中国胶片手套行业市场