c++文字列の分割

624 ワード

例:str="1_2_3_4"
呼び出しvector splitname=split_stri(str,"_");
結果splitname=["1","2","3","4"]
static vector split_str(string str, string pattern)
{
    string::size_type pos;
    vector result;
    str += pattern;
    size_t size = str.size();
    for(size_t i = 0; i < size; i++)
    {
        pos = str.find(pattern,i);
        if(pos < size)
        {
            string s = str.substr(i,pos-i);
            result.push_back(s);
            i = pos + pattern.size() - 1;
        }
    }
    return result;
}