Linux 分割字符串

 

C++ 存入map中

#include 
#include 
#include 
#include 

using namespace std;
/**
 * Split string to array
 * @param str -- the string need to be splited.
 * @param vec -- vector use to store splited string item.
 * @param splitChar -- the split character
 */
void splitStr(const string &str, vector &vec, const string &splitChar)
{
    string::size_type pos = str.find(splitChar);
    string::size_type pos1 = 0;
    while(string::npos !=  pos)
    {
        vec.push_back(str.substr(pos1, pos -pos1));
        pos1 = pos + splitChar.size();
        pos = str.find(splitChar, pos1);
    }
    if(pos1 != str.length())
    {
        vec.push_back(str.substr(pos1));
    }
}

int main()
{
    string msg = "aaaaa:bbbbbbbb";
    //分割
    vector vec;
    map str_map;
    splitStr(msg, vec, ":");
    //遍历
    int i=0;
    for(i=0; i< vec.size(); i++)
    {
        cout << vec[i] << endl;
    }
    //存入map中
    str_map.insert(pair(vec[0], vec[1]));

    map::iterator it;
    for(it = str_map.begin();it!=str_map.end();it++)
    {
        cout<first<<" "<second<

C 存入到vector中

#include 
#include 
#include 
#include 
#include 

using namespace std;

int main(int argc, char *argv[])
{
    cout << "Hello World!" << endl;

    string str_input;
    cout<<"输入一串以逗号为分隔符的数字字符串:"<>str_input;
    vector nums;
    char *s_input = (char*)str_input.c_str();
    const char* split = ",";
    char *p = strtok(s_input, split);

    int a;
    while(p != NULL)
    {
        sscanf(p, "%d", &a);
        nums.push_back(a);
        p=strtok(NULL, split);
    }

    cout<<"输出得到的数字:"<

 

你可能感兴趣的:(Linux)