C++常用的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按行讀取,再用這兩個函數分解成想要的子串。


免責聲明!

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



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