C++笔记string容器介绍

2022-07-30 14:17:19

目录

一,string构造函数

二,赋值操作

三,字符串拼接

四,字符串查找与替换

五,字符串比较

六,字符存取

七,字符串插入和删除

八,字串获取

使用操作——从邮箱地址中获取用户名信息


前提:

使用string容器要包含头文件

#include<string>

本质:

  •   string是C++风格的字符串,而string本质上是一个类。

string和char*的区别:

  •  char*是一个指针。
  •  string是一个类,类内封装了char*,管理这个字符串,是一个char*型的容器。

一,string构造函数

  1. string s1;  //创建空字符串

         const char* str = "hello world";

         string s2(str);    //初始化

      2.string s3(s2);    //使用一个string对象初始化另一个string对象

      3.string s4(5, 'a');     //使用n个字符a初始化

                            //string(int n,char c);

二,赋值操作

  1. string s1;

         s1 = "hello world";  //char*型字符串,赋值给当前字符串

2. string s2 = s1;  //字符串s1,赋值给s2

3. string s3;

          s3 = 'a';  //字符赋值给当前字符串

4.string s4;

           s4.assign("hello world");  //字符串s赋值给当前字符串

5. string s5;

           s5.assign("hello world", 5);  //把字符串s的前n个字符赋值给当前字符串

6.string s6;

           s6.assign(s5);//把字符串s赋值给当前字符串

 7.string s7;

           s7.assign(10, 'a');  //把n个字符c赋值给当前字符串

三,字符串拼接

  1.    string s1="独取";

         s1 += "一瓢C++";

 2.    s1 += ';';  //追加一个字符

 3.  string s2="lol我是";

            s2 += s1;

 4.   string s3="i";

s3.append(" love ");

 5.   s3.append("gamesferg", 5);  //把字符串s的前n个字符拼接到当前字符串

 6.    s3.append(s2);

 7.   s3.append(s2,0,3);   //从第0个位置,截取三个字符

四,字符串查找与替换

1,查找

     string s1 = "abcdefg";

     int p1=s1.find("de");

     /* 查找字符串在当前字符串的位置,默认是从第0个位置开始查找,

     find函数返回值是整形数据,若未找到,则返回-1 */

      int p2 = s1.rfind("de");

     /* find 和 rfind 都可实现查找功能,但区别是:

     find是从左往右查找,rfind是从右往左 */

2,替换

s1.replace(1, 3, "11111");

     /* replace函数有三个参数,从第1个位置开始,

     3个字符替换为“11111”*/

五,字符串比较

      string s1 = "hello";

      string s2 = "hello";

      int n =s1.compare(s2);

 比较方式:

  • 字符串比较是按照字符的ASCII码,逐个进行比较,直到比出大小结束

两个字符串相等                            返回  0

第一个字符串大于第二个字符串    返回  1

第一个字符串小于第二个字符串    返回  -1

六,字符存取

1,通过 [] 访问单个字符

       string s1 = "hello";

      for (int i = 0; i < s1.size(); i++) {

             cout << s1[i] << " ";

      }

      修改字符

      s1[0] = 'x';

2,通过at方式访问单个字符

      for (int i = 0; i < s1.size(); i++) {

            cout << s1.at(i) << " ";

      }

      修改字符

      s1.at(0) = 'x';

七,字符串插入和删除

1,,字符串插入

       string s1 = "hello";

s1.insert(1, "111");  //从第一个位置插入字符串

2,字符串删除

       s1.erase(1, 3);   //从第一个位置删除3个字符

八,字串获取

功能描述:

  • 从字符串中获取想要的子串

      string s1 = "hello";

      string s2 = s1.substr(1, 3);

      cout << s2;

使用操作——从邮箱地址中获取用户名信息

      string email = "zhangsan@qq.com";

      int pos = email.find("@");            //查找字符“@”的位置

      string userName = email.substr(0, pos);     //从第0个位置开始,获取pos个字符

      cout << userName << endl;

  • 作者:独取一瓢C++
  • 原文链接:https://blog.csdn.net/m0_63134260/article/details/122786152
    更新时间:2022-07-30 14:17:19