本質;string是c++風格的字符串,而string本質上是一個類
string和char*的區別:
- char*是一個指針;
- string是一個類,類內部封裝了char*,管理這個字符串,是一個char*的容器;
特點:
string內部封裝了很多內部成員方法,例如find、copy、delete、replace、insert等。
string管理char*所分配的內存,不用擔心復制越界和取值越界等,由類內部進行操作。
一、string構造函數
- string():創建一個空的字符串
- string(const char* s):使用字符串s初始化
- string(const string& str):使用一個string對象初始化另一個string對象
- string(int n,char c):使用n個字符c初始化
-
#include<iostream> #include<string> using namespace std; void test() { string s1;//默認構造 const char* str = "hello world"; string s2(str); cout <<"s2="<< s2 << endl; string s3(s2); cout << "s3=" << s3 << endl; string s4(10, 'a'); cout << "s4=" << s4 << endl; } int main() { test(); system("pause"); return 0; }
二、string賦值操作
#include<iostream> #include<string> using namespace std; void test() { string str1; str1 = "hello world"; cout << "str1=" << str1 << endl; string str2; str2 = str1; string str3; str3 = 'c'; string str4; str4.assign("hello woeld"); string str5; str5.assign("hello world", 5);//只賦值前n個字符 string str6; str6.assign(str5); string str7; str7.assign(10, 'w');//賦值十個w } int main() { test(); system("pause"); return 0; }
三、字符串拼接
#include<iostream> #include<string> using namespace std; void test() { string str1; str1 = "我"; str1 += "愛中國"; cout << "str1=" << str1 << endl; str1 += '!'; cout << "str1=" << str1 << endl; string str2 = "LOL"; str1 += str2; cout << "str1=" << str1 << endl; string str3 = "i"; str3.append(" love you"); cout << "str3=" << str3 << endl; str3.append("new gameing",4);//拼接前n個字符 str3.append(str2); str3.append(str2, 0, 2);//只截取第0,1個字符並拼接 cout << "str3=" << str3 << endl; } int main() { test(); system("pause"); return 0; }
三、字符串的查找和替換
#include<iostream> #include<string> using namespace std; void test() { //1.查找 string str1 = "abcdefg"; //find、rfind只找到第一個出現的位置 cout << str1.find("bc", 0) << endl;//默認從零位置開始,並返回找到的索引位置,未找到返回-1 cout << str1.rfind("bc",6) << endl;//rfind是從右往左查找,6是起始索引位置 //2.替換 str1.replace(0, 2, "pppp");//將0-1之間的位置替換成"pppp" cout << str1 << endl; } int main() { test(); system("pause"); return 0; }
四、字符串比較
#include<iostream> #include<string> using namespace std; void test() { string str1 = "hello"; string str2 = "hello"; //逐一比較每個字符的ASCII,若全部相等,返回0,若str1的ASCII大於str2則返回1,否則返回-1 str1.compare(str2); } int main() { test(); system("pause"); return 0; }
五、字符串的存取
#include<iostream> #include<string> using namespace std; void test() { string str1 = "hello"; //讀 cout << str1[0] << endl;; cout << str1.at(0) << endl; //寫 str1[0] = 'm'; cout << str1 << endl; str1.at(0) = 'p'; cout << str1 << endl; } int main() { test(); system("pause"); return 0; }
六、字符串的插入與刪除
void test() { string str1 = "hello"; str1.insert(1, "big");//在某個位置插入 cout << str1 << endl; str1.erase(1, 3);//刪除起始位置和最終位置之間的 cout << str1 << endl; }
七、子串獲取
void test() { string str1 = "hello"; cout << str1.substr(1, 3) << endl;//返回1-3之間的子串,包含下標1,2,3 }