栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

C++笔记——string容器介绍

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++笔记——string容器介绍

目录

一,string构造函数

二,赋值操作

三,字符串拼接

四,字符串查找与替换

五,字符串比较

六,字符存取

七,字符串插入和删除

八,字串获取

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


前提:

使用string容器要包含头文件

#include

本质:

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

string和char*的区别:

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

一,string构造函数

    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);

二,赋值操作

    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赋值给当前字符串

三,字符串拼接

       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");

     

 

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

     

2,替换

      s1.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;

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/729689.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号