C++ stl string 實現的字符串拆分函數


 1 //字符串拆分
 2 void split(string s,char splitchar,vector<string>& vec)
 3 {
 4     if(vec.size()>0)//保證vec是空的
 5         vec.clear();
 6     int length = s.length();
 7     int start=0;
 8     string topush;
 9     for(int i=0; i<length; i++)
10     {
11         if(s[i] == splitchar && i == 0)//第一個就遇到分割符
12         {
13             start += 1;
14         }
15         else if(s[i] == splitchar)
16         {
17             topush=s.substr(start,i - start);
18             if(topush.length()>0)
19                 vec.push_back(topush);
20             start = i+1;
21         }
22         else if(i == length-1)//到達尾部
23         {
24             topush=s.substr(start,i+1 - start);
25             if(topush.length()>0)
26                 vec.push_back(topush);
27         }
28     }
29 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM