代碼示例:
- #include <iostream>
- #include "string"
- using namespace std;
- //字符串初始化
- void strInit()
- {
- cout << "字符串初始化:" <<endl;
- string s1 = "abcdefg"; //初始化方式1
- string s2("abcdefg"); //初始化方式2
- string s3 = s2; //通過拷貝構造函數 初始化s3
- string s4(7,'s'); //初始化7個s的字符串
- cout << "s1 = "<< s1 << endl;
- cout << "s2 = "<< s2 << endl;
- cout << "s3 = "<< s3 << endl;
- cout << "s4 = "<< s4 << endl;
- }
- //字符串遍歷
- void strErgo()
- {
- cout << "字符串遍歷:" <<endl;
- string s1 = "abcdefg"; //初始化字符串
- //通過數組方式遍歷
- cout << "1、通過數組方式遍歷:" <<endl;
- for (int i = 0; i < s1.length(); i++)
- {
- cout << s1[i] << " ";
- }
- cout << endl;
- //通過迭代器遍歷
- cout << "2、通過迭代器遍歷:" <<endl;
- for(string::iterator it = s1.begin(); it!= s1.end(); it++)
- {
- cout << *it << " ";
- }
- cout << endl;
- //通過at()方式遍歷
- cout << "3、通過at()方式遍歷:" <<endl;
- for (int i = 0; i < s1.length(); i++)
- {
- cout << s1.at(i) << " "; //此方式可以在越界時拋出異常
- }
- cout << endl;
- }
- //字符指針和字符串的轉換
- void strConvert()
- {
- cout << "字符指針和字符串的轉換:" <<endl;
- string s1 = "abcdefg"; //初始化字符串
- cout << "string轉換為char*:" <<endl;
- //string轉換為char*
- cout << s1.c_str() <<endl; //s1.c_str()即為s1的char *形式
- cout << "char*獲取string內容:" <<endl;
- //char*獲取string內容
- char buf[64] = {0};
- s1.copy(buf, 7);//復制7個元素
- cout << buf <<endl;
- }
- //字符串連接
- void strAdd()
- {
- cout << "字符串連接:" <<endl;
- cout << "方式1:" <<endl;
- string s1 = "123";
- string s2 = "456";
- s1 += s2;
- cout << "s1 = "<< s1 << endl;
- cout << "方式2:" <<endl;
- string s3 = "123";
- string s4 = "456";
- s3.append(s4);
- cout << "s3 = "<< s3 << endl;
- }
- int main()
- {
- //初始化
- strInit();
- cout << endl;
- //遍歷
- strErgo();
- cout << endl;
- //字符指針類型和字符串轉換
- strConvert();
- cout << endl;
- //字符串連接
- strAdd();
- cout << endl;
- system("pause");
- return 0;
- }
程序運行結果:
- 字符串初始化:
- s1 = abcdefg
- s2 = abcdefg
- s3 = abcdefg
- s4 = sssssss
- 字符串遍歷:
- 1、通過數組方式遍歷:
- a b c d e f g
- 2、通過迭代器遍歷:
- a b c d e f g
- 3、通過at()方式遍歷:
- a b c d e f g
- 字符指針和字符串的轉換:
- string轉換為char*:
- abcdefg
- char*獲取string內容:
- abcdefg
- 字符串連接:
- 方式1:
- s1 = 123456
- 方式2:
- s3 = 123456
- 請按任意鍵繼續. . .
