c ++标记化std字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12627262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c++ tokenize std string
提问by Daniel Del Core
Possible Duplicate:
How do I tokenize a string in C++?
可能的重复:
如何在 C++ 中标记字符串?
Hello I was wondering how I would tokenize a std string with strtok
你好,我想知道如何用 strtok 标记一个 std 字符串
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
我正在寻找一种快速简便的方法,因为我认为它不需要太多时间
回答by PiotrNycz
I always use getline
for such tasks.
我总是getline
用于此类任务。
istringstream is(line);
string part;
while (getline(is, part, ','))
cout << part << endl;
回答by Pete Becker
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
.
要找到下一个标记,请重复find_first_of
但从 开始pos + 1
。
回答by spencercw
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++.
您可以使用strtok
by&*line.begin()
来获取指向char
缓冲区的非常量指针。我通常更喜欢boost::algorithm::split
在 C++ 中使用。
回答by Mike Seymour
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.
strtok
是一个相当古怪的、邪恶的函数,它修改了它的参数。这意味着您不能直接在 a 的内容上使用它std::string
,因为无法从该类中获取指向可变的、以零结尾的字符数组的指针。
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:
或者,对于更多的 C++ 习惯用法,您可以使用字符串流:
std::stringstream ss(line);
std::string token;
std::readline(ss, token, ',');
or find the comma more directly:
或者更直接地找到逗号:
std::string token(line, 0, line.find(','));