C++ string类的常用函数总结

C++ string类的常用函数总结,第1张

C++ string类的常用函数总结

本文主要用于分享并记录一些string的常用函数

每一个函数都有详细的注释辅助理解

#include
#include
using namespace std;
int main()
{
    string a = "abcdefgh";
    string b;
    int n = a.size();
    cout << "字符串a的长度为:" << n << endl;
    //判断字符是否为空
    //empty()
    if (b.empty() == 1)
        cout << "字符串b为空"<     else
        cout << "字符串b不为空"<     //求子串
    //substr()
    //substr(int pos,int n)
    //从pos开始的n个字符组成的字符串,字符串从0位开始
    cout << "输出字串:" << endl;
    string a1 = a.substr(2);//cdefgh
    string a2 = a.substr(2, 3);//cde
    cout << "a1=" << a1 << endl;
    cout << "a2=" << a2 << endl;
    //删除字符  
    // erase()
    //每次删除原串也会进行删除,从0开始标号
    cout << "输出删除以后的字符串:" << endl;
    string s = "hello,world!";
    string ss1 = s.erase(6);    //删除下标为6的字符开始的所有字符  hello,
    string ss2 = s.erase(1, 2);    //删除下标为1的字符开始的2个字符,删除el 
    cout << "s=" << s << endl;
    cout << "ss1=" << ss1 << endl;
    cout << "ss2=" << ss2 << endl;
    //插入字符
    //insert()在下标为i的前面加
    string q = ",";
    cout << "插入字符:" << endl;
    q.insert(0, "heo"); cout << q << endl;//在0的位置插入
    q.insert(4, "world", 2); cout << q << endl;//在4的位置插入world的前2个字符
    q.insert(2, 2, 'l'); cout << q << endl;//在2的位置插入单个字符2次 
    q.insert(q.end(), 'r'); cout << q << endl;//使用迭代器
    q += "ld!"; cout << q << endl;//在开头或者末尾插入最好还是运算符
    //查找
    //find()
    cout << "查找:" << endl;
    string t = "abcbcdefg";
    cout << t.find('c') << endl;
    cout << t.find("bcd") << endl;
    cout << t.find('e', 2) << endl;//从下标为2开始搜
    if (t.find("cd") != -1)//没找到值为-1或者a.npos
        cout << "找到了"<     else
        cout << "没找到" << endl;
    //替换字符串
    //replace()
    cout << "替换字符串:" << endl;
    string str = "abcdefghigk";
    str = str.replace(str.find("c"), 5, "#");  //从第一个c位置开始的五个字符替换成#
    cout << str << endl;

    string str1 = "he is@ a@ good boy";
    string substr = "12345";
    //前两个变量为str1的指定字符串
    str1 = str1.replace(0, 5, substr, substr.find("1"), 2); //用substr的指定字符串替换str指定字符串
    cout << str1 << endl;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5714369.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存