C++分割字符串

C++分割字符串,第1张

从这里拿来改进了点,亲测可用。

/**
 * @brief 按照分隔符对源字符串进行分割,分割结果存放到vector里,不会破坏源字符串
 * 
 * @param sourceStr 要被分割的源字符串
 * @param delimiter 分隔符
 * @param result 用于存储分割结果
 */
void stringSplit(const std::string& sourceStr, const std::string& delimiter, std::vector<std::string>& result)
{
    size_t last = 0;
    size_t next = 0;
    std::string token;
    while ((next = sourceStr.find(delimiter, last)) != std::string::npos)
    {
        if (next > last)
        {
            token = sourceStr.substr(last, next-last);
            result.push_back(token);
        }
        
        last = next+delimiter.length();
    }

    if (last < sourceStr.length())
    {
        token = sourceStr.substr(last);
        result.push_back(token);
    }
}

测试如下,

int main(void)
{
    std::string s = "scott>=tiger>=mushroom";
    std::string delimiter = ">=";
    std::vector<std::string> result;

    stringSplit(s, delimiter, result);

    for (auto it = result.cbegin(); it != result.cend(); ++it)
    {
        std::cout << *it << "\n";
    }

    return 0;
}

结果如下,

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

原文地址: https://outofmemory.cn/langs/872627.html

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

发表评论

登录后才能评论

评论列表(0条)

保存