C++ string 操作

c++中对string的split,trim,find操作:

 1 //分割字符串
 2 void splitString(string& word, string p, vector<string>& res){
 3     size_t last = 0;
 4     size_t index = word.find_first_of(p,last);
 5 
 6     string str;
 7     while(index != string::npos){
 8         str = word.substr(last,index-last);
 9         if(str.size() > 0)
10         res.push_back(str);
11         last = index+1;
12         index = word.find_first_of(p,last);
13     }
14 
15     if(index-last > 0){
16         str = word.substr(last,index-last);
17         if(str.size() > 0)
18             res.push_back(str);
19     }
20 }
21 
22 //去掉字符串中的空格
23 void trimString(string& word){
24     string ss = "\n\t\r ";
25     string str;
26     for(size_t i=0; i<ss.size(); i++){
27         str = ss.substr(i,1);
28         while(true){
29             size_t p = word.find(str);
30             if(p != string::npos) word.erase(p,1);
31             else break;
32         }
33         if(word == "") return;
34     }
35 }
36 
37 //计算字符串出现次数
38 int findString(string word, string p){
39     int count = 0;
40     string temp = word;
41     while(true){
42         size_t sp = temp.find(p);
43         if(sp == string::npos) break;
44         count++;
45         temp = word.substr(sp+p.size());
46     }
47 
48     return count;
49 }

 

posted @ 2015-12-02 10:40  流浪集  阅读(187)  评论(0编辑  收藏  举报