目录字符串切割的两种方法1、通过stl实现2、通过使用strtok()函数实现字符串分割&类型转换(string->double)字符串切割的两种方法 字符串切割的使用
字符串切割的使用频率还是挺高的,string本身没有提供切割的方法,但可以使用stl提供的封装进行实现或者通过c函数strtok()函数实现。
涉及到string类的两个函数find和substr:
1、find函数
2、substr函数
代码如下:
std::vector<std::string> splitWithStl(const std::string &str,const std::string &pattern)
{
std::vector<std::string> resVec;
if ("" == str)
{
return resVec;
}
//方便截取最后一段数据
std::string strs = str + pattern;
size_t pos = strs.find(pattern);
size_t size = strs.size();
while (pos != std::string::npos)
{
std::string x = strs.substr(0,pos);
resVec.push_back(x);
strs = strs.substr(pos+1,size);
pos = strs.find(pattern);
}
return resVec;
}
代码如下:
std::vector<std::string> split(const std::string &str,const std::string &pattern)
{
//const char* convert to char*
char * strc = new char[strlen(str.c_str())+1];
strcpy(strc, str.c_str());
std::vector<std::string> resultVec;
char* tmpStr = strtok(strc, pattern.c_str());
while (tmpStr != NULL)
{
resultVec.push_back(std::string(tmpStr));
tmpStr = strtok(NULL, pattern.c_str());
}
delete[] strc;
return resultVec;
};
【自己备用】
代码如下(示例):
#include<sstring>//头文件
#include<iOStream>
using namespace std;
int main()
{
string line;
ifstream is("2011_6.txt");
while(is>>line)
{
cout<<line<<endl;
istringstream is1(line.substr(line.find("C")+2,line.find(",")-2)); //创建一个istringstream对象,目的是将()中的字符串转换为数字型
// cout<<line.find("C")<<" "<<line.find(",")<<endl;
double o_x, o_y, r;
is1>>o_x; //将转换后的数字输入o_x
cout<<o_x<<endl;
line.erase(line.find("C"),line.find(",")+1); //将字符串中已经用过的部分擦除,为后面的字符串处理提供便利
cout<<line<<endl;
//cout<<line.find(",")<<endl;
istringstream is2(line.substr(0,line.find(",")));
is2>>o_y;
cout<<o_y<<endl;
line.erase(0,line.find(",")+1);
cout<<line<<endl;
istringstream is3(line.substr(0,line.find(";")));
is3>>r;
cout<<r<<endl;
line.erase(0,line.find(";")+1);
cout<<line<<endl;
}
}
substr(m,n)
表示从位置m开始截取n个字符,返回字符串,m默认0erase(m,n)
表示从位置m开始擦除n个字符,返回字符串,m默认0find(字符a)
表示返回字符a所在的位置以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: C++实现字符串切割的两种方法
本文链接: https://www.lsjlt.com/news/153095.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0