stl string 使用指定的分隔符分割成数个子字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
 
using namespace std;
 
void StringSplit(const string& str,vector<string>& vStr,const char& division)
{
    int startPos = 0;
    int endPos = string::npos;
         
    startPos = str.find_first_not_of(division);
    while(startPos != string::npos)
    {
        endPos = str.find_first_of(division,startPos);
        if(endPos != string::npos)
        {
            string strSplit = str.substr(startPos,(endPos-startPos));
            vStr.push_back(strSplit);
        }else
        {
            string strSplit = str.substr(startPos);
            vStr.push_back(strSplit);
        }
        startPos = str.find_first_not_of(division,endPos );
    }
 
 
    return;
}
 
 
void PrintElement(const string& str)
{
    cout << str << endl;
}
 
 
 
 
int _tmain(int argc, _TCHAR* argv[])
{
    string str1 = "_1_dfg45d#$__123456789_1_dfg45d#$__123456789_1_dfg45d#$__123456789_1_dfg45d#$__123456789_1_dfg45d#$__123456789";
    string str2 = "__sdfsf_dfg45d#$__张三李四____sdfsf_dfg45d#$__张三李四____sdfsf_dfg45d#$__张三李四____sdfsf_dfg45d#$__张三李四__";
    string str3 = "(*^(*^(*_dfg45d#$__天天向上__(*^(*^(*_dfg45d#$__天天向上__(*^(*^(*_dfg45d#$__天天向上__(*^(*^(*_dfg45d#$__天天向上__";
    vector<string> vStr;
    StringSplit(str1,vStr,'_');
    for_each(vStr.begin(),vStr.end(),PrintElement);
    cout << endl;
    vStr.clear();
 
    StringSplit(str2,vStr,'_');
    for_each(vStr.begin(),vStr.end(),PrintElement);
    cout << endl;
    vStr.clear();
 
    StringSplit(str3,vStr,'_');
    for_each(vStr.begin(),vStr.end(),PrintElement);
    cout << endl;
    vStr.clear();
    return 0;
}

  

posted on   itdef  阅读(777)  评论(0编辑  收藏  举报

努力加载评论中...

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示