1 //string字符串查找和替换 比较 存取 修改单个字符 插入和删除 string字串 2 #include <iostream> 3 #include<string> 4 5 using namespace std; 6 //查找 7 8 void test01() 9 { 10 string str1 = "abcdefg"; 11 12 int pos =str1.find("de"); 13 14 if (pos == -1) 15 { 16 cout << "没有找到<<endl;" <<endl; 17 } 18 else 19 { 20 cout << "找到字符串的位置,pos=" << pos << endl; 21 } 22 23 cout << "pos = " << pos << endl; 24 25 //rfind 和 find 区别 26 //rfind从右往左查找 find从左往右查找 27 pos = str1.rfind("de"); 28 cout << "pos" << pos << endl; 29 30 31 32 } 33 34 //替换 35 void test02() 36 { 37 string str1 = "abcdefg"; 38 39 //从1号位置起 3个字符 替换为“1111” 40 str1.replace(1, 3, "2222"); 41 cout << "str1 = " << str1 << endl; 42 } 43 44 //比较 45 // = 0 >1 <-1 46 void test03() 47 { 48 string str3 = "xhello"; 49 string str4 = "hellllo"; 50 51 if (str3.compare(str4) == 0) 52 { 53 cout << "str1等于 str2" << endl; 54 } 55 else if (str3.compare(str4) > 0) 56 { 57 cout << "str3 大于 str4 " << endl; 58 } 59 else 60 { 61 cout << "str3 小于 str4 " << endl; 62 } 63 64 } 65 66 //string 字符存取 67 void test04() 68 { 69 string str = "hello"; 70 //cout << "str = " << str << endl; 71 72 //第一种通过[]访问单个字符 73 for (int i = 0; i < str.size(); i++) 74 { 75 cout << str[i] << " "; 76 } 77 cout << endl; 78 79 //第二种通过at访问单个字符 80 for (int i = 0; i < str.size(); i++) 81 { 82 cout << str.at(i) << " "; 83 } 84 cout << endl; 85 86 //修改单个字符 87 str[0] = 'x'; 88 cout << "str = " << str << endl; 89 90 str.at(1) = 'z'; 91 cout << "str = " << str << endl; 92 93 } 94 95 //string 插入和删除 96 97 void test05() 98 { 99 string str8 = "hello"; 100 101 //插入 102 str8.insert(1, "111"); 103 cout << "str8 = " << str8 << endl; 104 105 //删除 106 str8.erase(1, 3); 107 cout << "str8 = " << str8 << endl; 108 109 } 110 111 //string 求字串 112 void test6() 113 { 114 string str = "ancdef"; 115 116 string subStr = str.substr(1, 3); 117 118 cout << "subStr = " << subStr << endl; 119 } 120 121 //使用操作 122 void test7() 123 { 124 string email = "zhangsan@qq.com"; 125 //从邮件地址中 获取 用户信息 126 127 int pos = email.find("@"); //8 128 cout << "emial pos = " << pos << endl; 129 130 string userName = email.substr(0, pos); 131 cout << "userName = " << userName << endl; 132 } 133 134 int main() 135 { 136 //test01(); 137 //test02(); 138 //test03(); 139 140 //test04(); 141 142 //test05(); 143 //test6(); 144 test7(); 145 }