C++ 在不使用 strtok() 的函数中拆分字符串 class
C++ split string class in function not using strtok()
我有一个默认的构造函数,它接受一个字符串 class 变量(而不是 char*
)并且需要用一个分隔符来标记该字符串,在我的特定情况下是一个逗号。由于我使用的是字符串 class,据我所知,我不能使用 strtok()
,因为它需要 char*
作为输入,而不是字符串 class。鉴于下面的代码,如果前两个标记是字符串,第三个是 in,第四个是 double
?
,我如何将字符串拆分成更小的字符串
private string a;
private string b;
private int x;
private double y;
StrSplit::StrSplit(string s){
a = // tokenize the first delimiter and assign it to a
b = // tokenize the second delimiter and assign it to b
x = // tokenize the third delimiter and assign it to x
y = // tokenize the fourth delimiter and assign it to y
}
试试下面的源代码:(test it online)
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <cstdlib>
std::string a;
std::string b;
int x;
double y;
std::vector<std::string> split(const std::string& s, char delimiter)
{
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(s);
while (std::getline(tokenStream, token, delimiter))
{
tokens.push_back(token);
}
return tokens;
}
int main()
{
std::string str = "hello,how are you?,3,4";
std::vector<std::string> vec;
vec = split(str, ',');
a = vec[0];
b = vec[1];
x = std::stoi(vec[2]); // support in c++11
x = atoi(vec[2].c_str());
y = std::stod(vec[2].c_str()); // support in c++11
y = atof(vec[2].c_str());
std::cout << a << "," << b << "," << x << "," << y << std::endl;
}
输出将是:
hello,how are you?,3,3
我有一个默认的构造函数,它接受一个字符串 class 变量(而不是 char*
)并且需要用一个分隔符来标记该字符串,在我的特定情况下是一个逗号。由于我使用的是字符串 class,据我所知,我不能使用 strtok()
,因为它需要 char*
作为输入,而不是字符串 class。鉴于下面的代码,如果前两个标记是字符串,第三个是 in,第四个是 double
?
private string a;
private string b;
private int x;
private double y;
StrSplit::StrSplit(string s){
a = // tokenize the first delimiter and assign it to a
b = // tokenize the second delimiter and assign it to b
x = // tokenize the third delimiter and assign it to x
y = // tokenize the fourth delimiter and assign it to y
}
试试下面的源代码:(test it online)
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <cstdlib>
std::string a;
std::string b;
int x;
double y;
std::vector<std::string> split(const std::string& s, char delimiter)
{
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(s);
while (std::getline(tokenStream, token, delimiter))
{
tokens.push_back(token);
}
return tokens;
}
int main()
{
std::string str = "hello,how are you?,3,4";
std::vector<std::string> vec;
vec = split(str, ',');
a = vec[0];
b = vec[1];
x = std::stoi(vec[2]); // support in c++11
x = atoi(vec[2].c_str());
y = std::stod(vec[2].c_str()); // support in c++11
y = atof(vec[2].c_str());
std::cout << a << "," << b << "," << x << "," << y << std::endl;
}
输出将是:
hello,how are you?,3,3