string类学习笔记

string类

  • string类的使用:#include< string >

  • string类的对象初始化

    1. string s1("hello");
    2. string s2 = "world";
    3. string s3 (8, 'x');
  • string类的常用成员函数

    1. length() / size(): 返回string对象的长度。

    2. assign(string s):string对象之间复制。

      //全部复制
      string s1 = "hello";
      string s2;
      s2.assign(s1);
      
      //部分复制
      s2.assign(s1, 1, 3); //从下标为1开始,复制3个字符
      
    3. at(int i):返回string对象第i个元素,并且会进行范围检查。

    4. append(string s):连接两个string对象。

      //全部连接
      string s1 = "good";
      string s2 = "morning";
      s1.append(s2);
      
      //部分连接
      s1.append(s2, 1, 8); //从下标为1开始,拼接8个字符。若s2没有足够字符则拼接到s2最后一个字符。
      
    5. compare(string s):比较两个string对象的大小。

      //相等result为0,大于result为1,小于result为-1
      //全部比较
      string s1 = "hello";
      string s2 = "heap";
      int result = s1.compare(s2); 
      
      //部分比较
      int result2 = s1.compare(1, 2, s2, 0, 3); //s1从下标1开始的两个字符与s2前3个字符比较
      
    6. substr(int start, int len):获得string对象的一个子串。

      string s1 = "hello wrold";
      string s2;
      s2 = s1.substr(4, 5); //s1从下标4开始的5个字符构成s2,若s1没有足够字符则数到s1最后一个字符。
      
    7. swap(string s):交换两个字符串。

      string s1 = "hello";
      string s2 = "world";
      s1.swap(s2);
      
    8. find(string s):从前往后查找子串第一次出现的位置。

      //找到返回子串第一个字符下标。找不到返回string::npos
      string s1 = "hello world";
      int index = s1.find("or");
      
    9. rfind(string s):从后往前查找。

    10. find(string s, int index):指定开始查找位置。

    11. find_first_of(string s):从前往后查找子串中任何一个字符第一次出现的位置。

      扫描二维码关注公众号,回复: 11164326 查看本文章
    12. find_last_of(string s):从前往后查找子串中任何一个字符最后一次出现的位置。

    13. find_first_not_of(string s):从前往后查找不在子串中的字母第一次出现的地方。

    14. find_last_not_of(string s):从前往后查找不在子串中的字母最后一次出现的地方。

    15. erase(int start):删除string对象中的字符。

      string s1 = "hello";
      s.erase(3); //删除下标为3之后的字符。
      
    16. replace(int start, int len, string s):替换string对象中的字符。

      //全部替换
      string s1 = "hello world";
      s1.replace(2, 3, "haha"); //将s1中从下标2开始的3个字符替换为"haha"。
      
      //部分替换
      s1.replace(2, 3, "haha", 1, 2); //只替换“haha”中下标1开始的2个字符。
      
    17. insert(int index, string s):在string对象中插入字符。

      //全部插入
      string s1 = "hello world";
      string s2 = "insert";
      s1.insert(5, s2); //将s2插入s1中下标为5的位置。
      
      //部分插入
      s1.insert(5, s2, 2, 3); //只插入s2中从下标2开始的3个字符。
      
    18. c_str() / data():将string对象转化为C风格字符串。

猜你喜欢

转载自www.cnblogs.com/leyoghurt/p/12815422.html