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按行读取,再用这两个函数分解成想要的子串。

posted @ 2019-07-18 21:11  charlee44  阅读(9073)  评论(0编辑  收藏  举报