C++常用的string字符串截断函数
程序员文章站
2022-07-05 08:42:54
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按行读取,再用这两个函数分解成想要的子串。
上一篇: ORA-28000: the account is locked-的解决办法
下一篇: ulimit