string容器(下)

六、string字符串比较

1、功能描述:字符串之间的比较

2、比较方式:字符串比较是按字符的ASCII码进行对比

  =     返回0

  >     返回1

  <     返回-1

3、函数原型:

(1)int compare(const string &s)const;  //与字符串s比较

(2)int compare(const char *s)const;  //与字符串s比较

4、代码

 1 #include <iostream>
 2 using namespace std;
 3 void test01()
 4 {
 5     string s1 = "hello";
 6     string s2 = "aello";
 7     int ret = s1.compare(s2);
 8     if (ret == 0)
 9     {
10         cout << "s1==s2" << endl;
11     }
12     else if (ret > 0)
13     {
14         cout << "s1大于s2" << endl;
15     }
16     else
17     {
18         cout << "s1小于s2" << endl;
19     }
20 }
21 int main()
22 {
23     test01();
24     return 0;
25 }

运行结果:

 七、string字符存取

1、函数原型:

char& operaotr[](int n);  //通过[]方式获取字符

char& at(int n);  //通过at方法获取字符

2、代码

 1 #include <iostream>
 2 using namespace std;
 3 #include <string>
 4 void test01()
 5 {
 6     string str = "hello world";
 7     for (int i = 0; i < str.size(); i++)
 8     {
 9         cout << str[i] << " ";
10     }
11     cout << endl;
12     for (int i = 0; i < str.size(); i++)
13     {
14         cout << str.at(i) << " ";
15     }
16     cout << endl;
17     str[0] = 'x';
18     str.at(1) = 'x';
19     cout << str << endl;
20 }
21 int main()
22 {
23     test01();
24     return 0;
25 }

运行结果:

 八、string插入和删除

1、功能描述:对string字符串进行插入和删除字符操作

2、函数原型:

  • string& insert(int pos, const char* s); //插入字符串
  • string& insert(int pos, const string& str); //插入字符串
  • string& insert(int pos, int n, char c); //在指定位置插入n个字符c
  • string& erase(int pos, int n = npos); //删除从Pos开始的n个字符

3、代码

 1 #include <iostream>
 2 using namespace std;
 3 #include <string>
 4 void test01()
 5 {
 6     string str = "hello";
 7     str.insert(1, "111");   //把pos=1的字符替换成“111”
 8     cout << str << endl;
 9     str.erase(1, 3);
10     cout << str << endl;
11 }
12 int main()
13 {
14     test01();
15     return 0;
16 }

运行结果:

 总结:插入和删除的起始下标都是从0开始

九、string子串

1、功能描述:从字符串中获取想要的字符串

2、函数原型:

  • string substr(int pos = 0, int n = npos) const; //返回由pos开始的n个字符组成的字符串

3、代码

 1 #include <iostream>
 2 using namespace std;
 3 #include <string>
 4 void test01()
 5 {
 6     string str = "abcdefg";
 7     string substr = str.substr(1, 3);   //获取从pos=1开始的三个字符
 8     cout << "substr=" << substr << endl;
 9 
10     string email = "hello@sina.com";
11     int pos = email.find("@");
12     string username = email.substr(0, pos);
13     cout << "username=" << username << endl;
14 }
15 int main()
16 {
17     test01();
18     return 0;
19 }

运行结果:

 

posted @ 2023-05-12 18:30  连师傅只会helloword  阅读(9)  评论(0编辑  收藏  举报