1 #include<iostream> 2 #include<string> 3 using namespace std; 4 //assign 5 void test01() 6 { 7 string str1; 8 //截取三个字符 9 str1.assign("hello,world", 3); 10 //从第三个字符开始截取4个字符 11 str1.assign("hello,world", 3, 4); 12 cout << str1; 13 cout << endl; 14 //同理append也是如此 15 cout << str1.append("hello,world", 5) << endl; 16 cout << str1.append("hello,world", 4, 5); 17 } 18 //repalce find rfind 19 void test02() 20 { 21 string str1 = "hello"; 22 //从第一个字符开始替换两个字符,同时插入一个字符串 23 str1.replace(1, 2, "22222"); 24 cout << str1 << endl; 25 str1 = "hello,world"; 26 //返回元素下标位置,找不到返回-1 27 int pos = str1.find("l"); 28 cout << "pos=" << pos << endl; 29 pos = str1.rfind('l'); 30 cout << "pos=" << pos << endl; 31 cout << str1.rfind("wo"); 32 } 33 //compare,insert size [] 34 void test03() 35 { 36 //compare比较字符串的ASCII值之和相等返回0,大于返回1,小于返回-1 37 string str1 = "hello"; 38 string str2 = "hello"; 39 int res = str1.compare(str2); 40 cout << res << endl; 41 //insert插入,从下表为4的元素前插入 42 str1.insert(4, "5555"); 43 cout << str1 << endl; 44 //size返回字符串元素个数 []取出str1中的元素 45 for (int i = 0; i < str1.size(); i++) 46 { 47 cout << str1[i]; 48 } 49 cout << endl; 50 51 } 52 //erase substr 53 void test04() 54 { 55 string str1 = "hello,world"; 56 //从下标为5的元素开始删除n个元素 57 str1.erase(5, 2); 58 cout << str1 << endl; 59 string str2=str1.substr(0, 5); 60 //从下标为0的元素开始返回5个字符 61 cout << str2 << endl; 62 } 63 64 int main() 65 { 66 /*test01();*/ 67 /*test02();*/ 68 /*test03();*/ 69 test04(); 70 return 0; 71 }
标签:string,str1,28,world,打卡,assign From: https://www.cnblogs.com/wlxdaydayup/p/17363920.html