C++ ——分割txt文本逗号,用到一些函数介绍

string 类成员函数:find ,substr,c_str()

1)find(const std::basic_string<char> &__str, optional size_type __pos);

第一个参数,字符串

第二个参数,可选参数,如果有,就是从pos位置开始,往后寻找指定的字符或是字符串

返回:找到 -- 返回 第一个字符的索引,没找到--返回   string::npos(代表 -1 表示不存在)

Example:

std::size_t found = str.find(str2);

  if (found!=std::string::npos) 

    cout<<found<<endl;

2) substr(size_type __pos, optional size_type __n)

通俗讲就是sub(start,length) 如果第二个参数不写,就是从start到字符串结尾

需要注意的是:比如说我们获得原字符串中从m-n的子串,那么应该写成(m,n-m+1);因为字符串下标是从0开始,而长度的计算是从1开始

Example:

string s("12345asdf");

string a=s.substr(0,5);

cout<<a<<endl;

获得字符串s中 从第0位开始的长度为5的字符串.默认时的长度为从开始位置到尾

3) c_str():生成一个const char*指针,指向以空字符终止的数组

这个数组应该是string类内部的数组

4)字符串转整型,长整型,double型:使用atoi()、 atil() 、atof()函数  ,实际上是char类型向数值类型的转换

代码:

void splitComma(vector<double>&wx, vector<double>&wy, const vector<string>& gpsData)
{
	const int cnt = 2;   //x,y,暂时没有yaw
	unsigned int j = 0;
	double temp1 = 0.0;
	double temp2 = 0.0;
	size_t comma = 0;
	size_t comma2 = 0;
	for (unsigned int g = 0; g < gpsData.size(); g++)
	{
		comma = gpsData[g].find(',', 0);
		temp1 = atof( gpsData[g].substr(0, comma).c_str() );
		wx.push_back(temp1);
		while (comma < gpsData[g].size() && j != cnt - 1)
		{
			comma2 = gpsData[g].find(',', comma + 1);
			//if (comma2 == std::string::npos)
			//{
			//}
			temp2 = atof(gpsData[g].substr(comma + 1, comma2 - comma - 1).c_str());
			/*cout << temp2 << ' ';*/
			wy.push_back(temp2);
			++j;
			comma = comma2;
		}
		cout << endl;
		j = 0;
	}
}

 

参考:

https://bbs.csdn.net/topics/390272890

https://blog.csdn.net/u012273127/article/details/61914627

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值