天天看點

C++ code:char pointers and char arrays(字元指針與字元數組)

C-串的正确指派、複制、修改、比較、連接配接等方式。

1 #include<iostream>
 2 #pragma warning(disable: 4996)//這一句是為了解決“strrev”出現的警告
 3 using namespace std;
 4 int main()
 5 {
 6     char* s1 = "Hello ";
 7     char* s2 = "123";
 8     char a[20];
 9     strcpy(a,s1);
10     cout << (strcmp(a, s1) == 0 ? "" : " not") << "equal\n";
11     cout << strcat(a, s2) << endl;
12     cout << strrev(a) << endl;
13     cout << strset(a, 'c') << endl; 
14     cout << (strstr(s1, "ell") ? "" : "not ") << "found\n";
15     cout << (strchr(s1, 'c') ? "" : "not ") << "found\n";
16     cin.get();
17     return 0;
18 }      

運作結果:

C++ code:char pointers and char arrays(字元指針與字元數組)

下面進入string:

string是一種自定義的類型,它可以友善地執行C-串不能直接執行的一切操作。它處理空間占用問題是自動的,需要多少,用多少,不像字元指針那樣,提心吊膽于指針脫鈎時的空間遊離。

1 #include<iostream>
 2 #include<string>
 3 #include<algorithm>
 4 using namespace std;
 5 int main()
 6 {
 7     string a,s1 = "Hello ";
 8     string s2 = "123";
 9     a=s1;//複制
10     cout << (a==s1 ? "" : " not") << "equal\n";//比較
11     cout << a + s2 << endl;//連接配接
12     reverse(a.begin(), a.end());//倒置串
13     cout << a << endl; 
14     cout << a.replace(0, 9, 9, 'c') << endl;//設定
15     cout << (s1.find("ell")!=-1 ? "" : "not ") << "found\n";//查找串
16     cout << (s1.find("c") != -1 ? "" : "not ") << "found\n";//查找字元
17     cin.get();
18     return 0;
19 }      

繼續閱讀