C++字符串划分

文章目录

代码

#include <iostream>
#include <sstream>
#include <vector>

/************
* 字符串划分
* 参数:
*	str:	待划分字符串
*   split: 划分字符串,默认为","
************/
std::vector<double> string_split(std::string str, std::string split=",")
{
	std::vector<double> ret_vec;

	// 暂存位置
	size_t pos = 0;
	// 暂存数字
	double num = 0;
	while ((pos = str.find(split)) != std::string::npos) {
		// 查找字符串并转换为数字
		num = atof(str.substr(0, pos).c_str());
		// 添加数字
		ret_vec.push_back(num);
		// 删除字符串已查找部分
		str.erase(0, pos + split.length());
	}
	// 把最后一个数字也要加进去
	ret_vec.push_back(atof(str.substr(0, pos).c_str()));
	
	return ret_vec;
}


/************
* 输出vector
************/
std::ostream& operator<<(std::ostream& cout, std::vector<double> vec)
{
	for (int i = 0; i < vec.size(); i++)
	{
		cout << vec[i] << " ";
	}
	cout << std::endl;
	return cout;
}


int main(void)
{
	std::string str = "1.2, 3.4, 4.5, 5.6";
	std::vector<double> vec = string_split(str);
	std::cout << vec;
	return 0;
}

输出

1.2 3.4 4.5 5.6

参考

【1】字符串划分
【2】字符串转数字

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值