当前位置:C++技术网 > 资讯 > string系列:7 string分割字符串split实现

string系列:7 string分割字符串split实现

更新时间:2016-10-18 09:45:30浏览次数:1+次

    我们经常会遇见这样的字符串:"100,200,110,201,30,14,10"。然后我们需要按照逗号将这个字符串提取为一系列的数字,放到数组中。当然,这里的逗号可以换成其他符号。这样的情况太常见了,今天又用到了。所以将写好的函数分享出来,供今后查阅使用。
    我这里提供两个版本,一个是直接将字符串按照分隔符分割成子字符串数组,一个是将字符串分割成整型数组(如果分割后不是整数,字符串会被处理成0)。

    下面是处理的效果图:

C++的string分割字符串split实现

C++的string分割字符串split实现

    下面是测试代码:


#include <iostream>
#include <vector>
using namespace std;
void main()
{
    string str="www,cjjjs,com,201,30,14,10";
    vector<string> vstr;
    vector<int> vint;
    cout<<"原始字符串:"<<str.c_str()<<endl;
    //分割为整型
    if(0==split2(str,vint,","))
    {
        for(size_t i=0;i<vint.size();i++)
        {
            cout<<i<<"  "<<vint[i]<<endl;
        }
    }
    //分割为字符串
    //if(0==split(str,vstr,","))
    //{
    //    //分割成功
    //    for(size_t i=0;i<vstr.size();i++)
    //    {
    //        cout<<i<<"  "<<vstr[i].c_str()<<endl;
    //    }
    //}
    system("pause");
}
    分割为字符串的函数split:



int split(const string& str, vector<string>& list, string sep_str)
{
    if (str.empty())return 0;
    string tmp;
    string::size_type pos_begin = str.find_first_not_of(sep_str);
    string::size_type comma_pos = 0;
    while (pos_begin != string::npos)
    {
        comma_pos = str.find(sep_str, pos_begin);
        if (comma_pos != string::npos)
        {
            tmp = str.substr(pos_begin, comma_pos - pos_begin);
            pos_begin = comma_pos + sep_str.length();
        }
        else
        {
            tmp = str.substr(pos_begin);
            pos_begin = comma_pos;
        }
        if (!tmp.empty())
        {
            list.push_back(tmp);
            tmp.clear();
        }
    }
    return 0;
}
    分割为整型的函数split2:



int split2(const string& str, vector<int>& list, string sep_str)
{
    vector<string> vstr;
    if (str.empty())return 0;
    string tmp;
    string::size_type pos_begin = str.find_first_not_of(sep_str);
    string::size_type comma_pos = 0;
    while (pos_begin != string::npos)
    {
        comma_pos = str.find(sep_str, pos_begin);
        if (comma_pos != string::npos)
        {
            tmp = str.substr(pos_begin, comma_pos - pos_begin);
            pos_begin = comma_pos + sep_str.length();
        }
        else
        {
            tmp = str.substr(pos_begin);
            pos_begin = comma_pos;
        }
        if (!tmp.empty())
        {
            vstr.push_back(tmp);
            tmp.clear();
        }
    }
    list.clear();
    for (size_t i=0;i<vstr.size();i++)
    {
        list.push_back(atoi(vstr[i].c_str()));
    }
    return 0;
}
    分割为整数的函数,内置一个转换,即将将字符串转为数字,我已直接内置到代码中了,便于整个函数使用。


    整个vector容器元素字符串转为整数代码如下:


void vstr2vint(vector<string> vstr,vector<int>& vint)
{
    vint.clear();
    for (size_t i=0;i<vstr.size();i++)
    {
        vint.push_back(atoi(vstr[i].c_str()));
    }
}
    我们这里的数组用的是vector容器,动态扩展,非常方便。如果你喜欢用传统的数组,可以自己改造代码。