美文网首页
C++ string常用接口

C++ string常用接口

作者: 林逸凡_lyf | 来源:发表于2018-05-21 21:07 被阅读0次
    substr
    string s = "abcdefg";
    string s2 = s.substr(1, 5); //s2 = "bcdefg", 从index 1向后截取5个字符
    string s3 = s.substr(4); //s3 = "efg", 从index 4截取到尾部
    
    insert
    string s = "1234567";
    string s2 = "abcdefg";
    s.insert(2, s2); //s = "12abcdefg34567", 在index 2之前插入s2
    s.insert(4, s2, 2, 3); //s = "1234cde567", 在index 4之前插入s2.substr(2, 3)
    s.insert(5, s2, 5); //s = "12345fg67", 在index 5之前插入s2.substr(5);
    s.insert(3, 4, "a"); //s = "123aaaa4567", 在index 3之前插入4个a
    
    erase
    string str = "abcdefg 1234567";
    str.erase(6, 4); // str = "abcdef34567", 从index 6开始,删除四个字符
    
    replace
    string s = "abcdefg";
    string s2 = "1234567";
    s.replace(3, 2, s2); //s = "abc1234567fg", 从index 3开始,将后面的2个字符替换为s2
    s.replace(4, 2, s2, 1, 4); //s = "abcd2345g", 从index 4开始,将后面的2个字符替换为s2.substr(1, 4)
    
    assign
    string str;
    str.assign("abcdefghijkl", 6); //str = "abcdef", 将前六个字符赋值给str
    str.assign("abcdefghijkl", 6, 5); //str = "ghijk", 将从index 6开始的5个字符赋给str
    str.assign(10, 'a'); //str = "aaaaaaaaaa", 给str赋值10个a
    
    find/rfind

    find是第一个匹配,rfind是最后一个匹配

    string str = "abcdefg";
    string sub = "cde";
    size_t found = str.find(sub);
    size_t found2 = str.find(sub, found+1);
    if (found == string::npos) {
        //没有找到
    }
    
    compare
    string s1 = "123";
    string s2 = "123";
    s1.compare(s2); //0
    s1 = "1234";
    s1.compare(s2); //1
    s2 = "12345";
    s1.compare(s2); //-1
    s1.compare(0, 3, "123"); //0, 比较s1从index 0开始的三个字符和参数
    
    数值转换
    int val = 100;
    string str = to_string(val); //s = "100", 将val转为string
    int val2 = stoi(str, 0, 10); //val2 = 100, 将str从0开始的位置转为10进制int
    // 类似的还有stof, stod...
    
    大小写
    string s = "abCdE";
    islower(s[1]); //isupper()
    s[3] = toupper(s[1]); //tolower()
    isalpha(int c); //判断是不是字母
    

    相关文章

      网友评论

          本文标题:C++ string常用接口

          本文链接:https://www.haomeiwen.com/subject/cigqjftx.html