c++分割字符串方法

c++分割字符串方法
强烈推介IDEA2020.2破解激活,IntelliJ IDEA 注册码,2020.2 IDEA 激活码
//分割字符串方法
//str 要分割的字符串
//pattern 分割的字符
//return StringList 分割后的集合
StringList splitstr(const std::string& str, const std::string& pattern)
{
    StringList  li;
    std::string subStr;
    std::string tPattern;
    size_t      patternLen =pattern.length();
    size_t      strLen     = str.length();
 
    for(size_t i = 0; i < str.length(); i++)
    {
        if(pattern[0] == str[i] && ((strLen - i) >= patternLen))
        {
            if(memcmp(&pattern[0],&str[i], patternLen) == 0)
            {
                i += patternLen - 1;
                if(!subStr.empty())
                {
                    li.push_back(subStr);
                    subStr.clear();
                }
            }
            else
            {
                subStr.push_back(str[i]);
            }
        }
        else
        {
            subStr.push_back(str[i]);
        }
    }
 
    if(!subStr.empty())
    {
        li.push_back(subStr);
    }
 
    return li;
}

//测试 使用换行分割
string text="fzy \n fzy";
StringList res = splitstr(text, "\n");
std::cout << "string list count:" << res.size() <<endl;
for(int i = 0; i < res.size(); i++)
{
    std::cout << res[i] << endl;
}

 

本文来源huayang183,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/18623

发表评论