zoukankan      html  css  js  c++  java
  • C++(十)— 字符串进行插入、替换、查找、删除操作、substr

     1、C++中对字符串进行插入、替换、删除操作

    #include<iostream>
    #include<algorithm>
    #include<stdio.h>
    #include <vector>
    #include<string>
    using namespace std;
    
    int main()
    {
        string s = "123456";
    
        // 在字符串指定位置前插入字符,
        cout << s.insert(2, "abc") << endl;// 输出 :12ab3456
    
        // 插入指定字符串的前n个字符
        cout << s.insert(2, "abc", 2) << endl;// 12ab3456
    
        //替换指定索引开始的指定长度的子串
        cout << s.replace(2, 2, "abc") << endl;// 12abc56,替换“34”为“abc”
    
        //删除指定索引开始的指定长度的字符
        string word = "34";
        size_t index = s.find(word); //查找,返回位置
        if (index != string::npos)
            cout << s.erase(index, word.length()) << endl;//1256,删除了"34"
    
        return 0;
    }

    2、substr与substring对比

    (1)substr

    1 、substr 方法用于返回一个从指定位置开始的指定长度的子字符串。substr(start [, length ])

    2 、截取直接长度的字符串。substr(2,3),从下标为2开始,截取长度为3的字符串。而substring(2,3),则是从下标为2开始,截取到下标为3的前一位的字符串,也就是截取1位字符。

    (2)substring

    1 、substring 方法用于提取字符串中介于两个指定下标之间的字符

    2、 substring(start,end) 开始和结束的位置,从零开始的索引

      end:字符串下标,结束符是不包括该下标的。比如substring(0,3),那就是从下标0开始,截取到下标为3的前一位(不包括下标为3的那个字符)

  • 相关阅读:
    Fortran编译器之一GUN Fortran安装(Windows XP)
    c++动态绑定的技术实现
    c++标准库比较
    java array
    java常用的基础容器
    mac sublime text 3 add ctags plugin
    git fetch
    查看远程分支的log
    git删除分支
    detached HEAD state
  • 原文地址:https://www.cnblogs.com/eilearn/p/9427027.html
Copyright © 2011-2022 走看看