C++的substr实现分割字符串

一、介绍

原型:string substr ( size_t pos = 0, size_t n = npos ) const;
形式 : str.substr(pos, len)
返回值: string,包含str中从pos开始的len个字符的拷贝(pos的默认值是0,len的默认值是s.size() - pos,即如果不加参数,会默认拷贝整个str)
异常 :若pos的值超过了string的大小,则substr函数会抛出一个out_of_range异常;若pos+n的值超过了string的大小,则substr会调整n的值,只拷贝到string的末尾

//substr有2种常用用法:
//假设:string s = “0123456789”;

string sub1 = s.substr(5); //只有一个数字5表示从下标为5开始一直到结尾:sub1 = “56789”

string sub2 = s.substr(5, 3); //从下标为5开始截取长度为3位:sub2 = “567”

二、分割字符串

使用

//字符串分割函数
std::vector<std::string> split(std::string str, std::string pattern)
{
    std::string::size_type pos;
    std::vector<std::string> result;
    str += pattern;//扩展字符串以方便操作
    int size = str.size();
    for (int i = 0; i < size; i++)
    {
        pos = str.find(pattern, i);
        if (pos < size)
        {
            std::string s = str.substr(i, pos - i);
            result.push_back(s);
            i = pos + pattern.size() - 1;
        }
    }
    return result;
}

int main()
{

    std::string str;
    std::cout << "Please input str:" << std::endl;
    std::cin >> str; // 输入字符串

    std::string pattern;
    std::cout << "Please input pattern:" << std::endl;
    std::cin >> pattern; // 分割符

    std::vector<std::string> result = split(str, pattern);
    std::cout << "The result:" << std::endl;
    for (int i = 0; i < result.size(); i++)
    {
        std::cout << result[i] << std::endl; // 打印
    }
    system("pause");
    return 0;
}

输出

 参考:

C++如何做字符串分割(5种方法)_卧_听风雨的博客-CSDN博客_c++ 字符串分割

C++中substr()函数用法详解_canonrreas的博客-CSDN博客_c++ substr

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值