C++字符串分割

字符串分割

在学习C语言时,分割字符串主要使用strtok()库函数;然而在学习C++之后,发现string类中没有strtok这个成员函数了,但有6个字符串搜索函数,这样可以利用搜索函数完成字符串分割。

string搜索操作:

函数名解释
s.find(args)查找s中第一次出现args的位置
s.rfind(args)查找s中最后一次出现args的位置
s.find_first_of(args)在s中查找args中任何一个字符第一次出现的位置
s.find_last_of(args)在s中查找args中任何一个字符最后一次出现的位置
s.find_first_not_of(args)在s中查找第一个不在args中的字符的位置
s.find_last_not_of(args)在s中查找最后一个不在args中的字符的位置

上面各函数返回指定字符串出现的下标,如果未找到则返回npos,其中npos为string类中的静态常数据成员,默认为-1。

args 参数形式必须是以下之一:

形式解释
c,pos从s中pos位置开始查找字符c。pos默认为0
str,pos从s中pos位置开始查找字符串str。pos默认为0
cp,pos从s中pos位置开始查找指针cp指向的以空字符结尾的C风格的字符串。pos默认为0
cp,pos,n从s中pos位置开始查找指针cp指向的数组的前n个字符。pos和n无默认值

下面看例子:
C语言字符串分割:

#include <iostream>
#include <string>
using namespace std;

int main()
{
	char str[] = "- This, a sample string.";
	char * pch;
	printf("Splitting string \"%s\" into tokens:\n", str);
	pch = strtok(str, " ,.-");
	while (pch != NULL)
	{
		printf("%s\n", pch);
		pch = strtok(NULL, " ,.-");
	}
	return 0;
}

C++字符串分割:

#include <iostream>
#include <string>
#include <cstddef>
#include <vector>
using namespace std;
namespace strg
{
    //函数模板
	template<typename Container>
	inline std::size_t strtok(std::string& str, Container& cont, const std::string defstr = " ")
	{
		cont.clear();
		std::size_t size = 0;
		std::size_t begpos = 0 ;
		std::size_t endpos = 0 ;
		begpos = str.find_first_not_of(defstr);
		while (begpos != std::string::npos)
		{
			size++;
			endpos = str.find_first_of(defstr, begpos);
			if (endpos == std::string::npos)
			{
				endpos = str.size();
			}
			std::string ssubstr = str.substr(begpos, endpos -begpos);
			cont.push_back(ssubstr);    //将分割的字符串存入容器当中
			begpos = str.find_first_not_of(defstr, endpos+1);
		}
		return size;
	}

	template<typename Container>
	inline size_t stringtok(std::string& str, Container& cont, const std::string defstr = " ")
	{
		cont.clear();
		std::size_t size = 0;
		std::size_t length = str.length();

		std::size_t begpos = 0;
		std::size_t endpos = 0;
		while (begpos < length)
		{
			size++;
			begpos = str.find_first_not_of(defstr,begpos);
			if (begpos == std::string::npos)
				return -1;
			endpos = str.find_first_of(defstr, begpos);
			if (endpos == std::string::npos)
			{
				endpos = length;
			}
			std::string ssubstr = str.substr(begpos, endpos - begpos);
			cont.push_back(ssubstr);

			begpos = endpos + 1;
		}
		return size;
	}
}

int main()
{
	std::string str =  "- This, a sample string.";
	vector<string> vec;
	int size = strg::strtok(str,vec,"-,. ");
	for (auto& it : vec)
		cout << it << " ";
	cout<< endl;
	system("pause");
	return 0;
}

## 参考:

  1. C++ primer(第五版)
  2. http://www.cplusplus.com/reference/string/string
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值