C++分割字符串

find substr分割

//分割字符串返回doubleVec
void splitString(string &s, vector<double> &vec, char ch = ' ')
{
	s += ch;
	int size = s.size();

	for ( int i = 0; i < size; ++i )
	{
		int pos = s.find(ch, i);
		if (pos < size)
		{
			string temp = s.substr(i, pos - i);
			vec.push_back(stod(temp));
			i = pos;
		}
	}

	s.pop_back();
//stod()  需要包含string头文件
//s += to_string(ch)  ch转换为数字
}

删除最后一个字符方法

string str;
//方法一:substr截取前(len - 1)内容返回新串
str = substr(0, str.length() - 1);

//方法二:erase()
str.erase(str.end() - 1);

//方法三:pop_back()
str.pop_back();

double和string互相转换

//string -> double
string str = "12.34567";
double d = 0;

//using std::stod
string::size_type size;
d = stod(str, &size);	//size = 8
cout << d << endl;

//using sstream  需要#include <sstream>
istringstream istrStream(str);
istrStream >> d;
cout << d << endl;

//using sscanf
int len;
sscanf_s(str.c_str(), "%8lf%n", &d, &len);
cout << d << endl;

//double -> string
double d = 1.12345;
string str;

//using std::to_string
cout << to_string(d) << endl;

//using sstream;
ostringstream ostrStream;
ostrStream << setprecision(3);
ostrStream << d;
str = ostrStream.str();
cout << str <<endl;

//using sprintf
char ch[64] = {0};
sprintf_s(ch, "%g", d);
str = ch;
cout << str << endl;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值