我试图用strtok()
C++ 中的函数获取令牌。当您仅使用 1 个分隔符时非常简单,例如:
token = strtok(auxiliar,"[,]");
. auxiliar
每当函数找到[
,,
或时,这将被切断]
。
我想要的是获得带有一系列分隔符的标记,例如:可以用函数[,]
来做吗?strtok
我找不到路。
谢谢!
如果您想strtok
将[,]
其视为单个令牌,则无法这样做。 strtok
始终将您在分隔符字符串中传递的任何内容视为单独的 1 字符分隔符。
除此之外,最好不要strtok
在 C++ 中使用。它不是可重入的(例如,你不能嵌套调用),不是类型安全的,并且很容易以产生讨厌的错误的方式使用。
最简单的解决方案是在循环中简单地搜索std::string
您想要的特定分隔符。如果您需要更复杂的功能,Boost 库中有分词器,我还发布了代码以仅使用标准库来进行更全面的分词,这里。
我上面链接的代码也将分隔符视为单个字符,但我认为代码可以按照您想要的方式进行扩展。
If this is really C++, you should use std::string and not C strings.
Here's an example that uses only the STL to split a std::string
into a std::vector
:
#include <cstddef>
#include <string>
#include <vector>
std::vector<std::string> split(std::string str, std::string sep) {
std::vector<std::string> vec;
size_t i = 0, j = 0;
do {
i = str.find(sep, j);
vec.push_back( str.substr(j, i-j) );
j = i + sep.size();
} while (i != str.npos);
return vec;
}
int main() {
std::vector<std::string> vec = split("This[,]is[[,]your, string", "[,]");
// vec is contains "This", "is[", "your, string"
return 0;
}
If you can use the new C++11 features, you can do it with regex and token iterators. For example:
regex reg("\[,\]");
const sregex_token_iterator end;
string aux(auxilar);
for(sregex_token_iterator iter(aux.begin(), aux.end(), reg); iter != end; ++iter) {
cout << *iter << endl;
}
This example is from the Wrox book Professional C++.
如果你可以使用 boost 库,我认为这会做你想做的事——虽然你的问题有点不清楚,但不完全确定
#include <iostream>
#include <vector>
#include <string>
#include <boost/tokenizer.hpp>
int main(int argc, char *argv[])
{
std::string data("[this],[is],[some],[weird],[fields],[data],[I],[want],[to],[split]");
boost::tokenizer<boost::char_separator<char> > tokens(data, boost::char_separator<char>("],["));
std::vector<std::string> words(tokens.begin(), tokens.end());
for(std::vector<std::string>::const_iterator i=words.begin(),end=words.end(); i!=end; ++i)
{
std::cout << '\'' << *i << "'\n";
}
return 0;
}
这会产生以下输出
'this'
'is'
'some'
'weird'
'fields'
'data'
'I'
'want'
'to'
'split'