c++ tokenize std string [duplicate]

2020-07-10 07:49发布

Possible Duplicate:
How do I tokenize a string in C++?

Hello I was wondering how I would tokenize a std string with strtok

string line = "hello, world, bye";    
char * pch = strtok(line.c_str(),",");

I get the following error

error: invalid conversion from ‘const char*’ to ‘char*’
error: initializing argument 1 of ‘char* strtok(char*, const char*)’

I'm looking for a quick and easy approach to this as I don't think it requires much time

4条回答
啃猪蹄的小仙女
2楼-- · 2020-07-10 08:33

I always use getline for such tasks.

istringstream is(line);
string part;
while (getline(is, part, ','))
  cout << part << endl;
查看更多
男人必须洒脱
3楼-- · 2020-07-10 08:36
std::string::size_type pos = line.find_first_of(',');
std::string token = line.substr(0, pos);

to find the next token, repeat find_first_of but start at pos + 1.

查看更多
迷人小祖宗
4楼-- · 2020-07-10 08:39

You can use strtok by doing &*line.begin() to get a non-const pointer to the char buffer. I usually prefer to use boost::algorithm::split though in C++.

查看更多
一纸荒年 Trace。
5楼-- · 2020-07-10 08:41

strtok is a rather quirky, evil function that modifies its argument. This means that you can't use it directly on the contents of a std::string, since there's no way to get a pointer to a mutable, zero-terminated character array from that class.

You could work on a copy of the string's data:

std::vector<char> buffer(line.c_str(), line.c_str()+line.size()+1);
char * pch = strtok(&buffer[0], ",");

or, for more of a C++ idiom, you could use a string-stream:

std::stringstream ss(line);
std::string token;
std::readline(ss, token, ',');

or find the comma more directly:

std::string token(line, 0, line.find(','));
查看更多
登录 后发表回答