C++中經常會用到標準庫函數庫(STL)的string字元串類,跟其他語言的字元串類相比有所缺陷。這裡就分享下我經常用到的兩個字元串截斷函數: include include include include using namespace std; //根據字元切分string,相容最前最後存在字元 ...
C++中經常會用到標準庫函數庫(STL)的string字元串類,跟其他語言的字元串類相比有所缺陷。這裡就分享下我經常用到的兩個字元串截斷函數:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
//根據字元切分string,相容最前最後存在字元
void CutString(string line, vector<string> &subline, char a)
{
//首字母為a,剔除首字母
if (line.size() < 1)
{
return;
}
if (line[0] == a)
{
line.erase(0, 1);
}
size_t pos = 0;
while (pos < line.length())
{
size_t curpos = pos;
pos = line.find(a, curpos);
if (pos == string::npos)
{
pos = line.length();
}
subline.push_back(line.substr(curpos, pos - curpos));
pos++;
}
return;
}
//根據空截斷字元串
void ChopStringLineEx(string line, vector<string> &substring)
{
stringstream linestream(line);
string sub;
while (linestream >> sub)
{
substring.push_back(sub);
}
}
int main()
{
string line = ",abc,def,ghi,jkl,mno,";
vector<string> subline;
char a = ',';
CutString(line, subline, a);
cout << subline.size()<<endl;
for (auto it : subline)
{
cout << it << endl;
}
cout << "-----------------------------" << endl;
line = " abc def ghi jkl mno ";
subline.clear();
ChopStringLineEx(line, subline);
cout << subline.size() << endl;
for (auto it : subline)
{
cout << it << endl;
}
return 0;
}
函數CutString根據選定的字元切分string,相容最前最後存在字元;函數ChopStringLineEx根據空截斷字元串。這兩個函數在很多時候都是很實用的,例如在讀取文本的時候,通過getline按行讀取,再用這兩個函數分解成想要的子串。