栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

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

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

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

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

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