作者:晴活的比较迷-茫m | 来源:互联网 | 2023-10-11 19:01
1 //string字符串查找和替换 比较 存取 修改单个字符 插入和删除 string字串
2 #include
3 #include
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 <<"没有找到< 17 }
18 else
19 {
20 cout <<"找到字符串的位置,pos=" < 21 }
22
23 cout <<"pos = " < 24
25 //rfind 和 find 区别
26 //rfind从右往左查找 find从左往右查找
27 pos = str1.rfind("de");
28 cout <<"pos" < 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 = " < 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" < 54 }
55 else if (str3.compare(str4) > 0)
56 {
57 cout <<"str3 大于 str4 " < 58 }
59 else
60 {
61 cout <<"str3 小于 str4 " < 62 }
63
64 }
65
66 //string 字符存取
67 void test04()
68 {
69 string str = "hello";
70 //cout <<"str = " < 71
72 //第一种通过[]访问单个字符
73 for (int i = 0; i 74 {
75 cout < 76 }
77 cout < 78
79 //第二种通过at访问单个字符
80 for (int i = 0; i 81 {
82 cout < 83 }
84 cout < 85
86 //修改单个字符
87 str[0] = 'x';
88 cout <<"str = " < 89
90 str.at(1) = 'z';
91 cout <<"str = " < 92
93 }
94
95 //string 插入和删除
96
97 void test05()
98 {
99 string str8 = "hello";
100
101 //插入
102 str8.insert(1, "111");
103 cout <<"str8 = " <104
105 //删除
106 str8.erase(1, 3);
107 cout <<"str8 = " <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 = " <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 = " <129
130 string userName = email.substr(0, pos);
131 cout <<"userName = " <132 }
133
134 int main()
135 {
136 //test01();
137 //test02();
138 //test03();
139
140 //test04();
141
142 //test05();
143 //test6();
144 test7();
145 }