gpt4 book ai didi

c++ - strtok 如何还包括分隔符作为标记

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:59:43 24 4
gpt4 key购买 nike

现在我已经设置了代码,将我的字符串分成带有分隔符 ,;= 和空格的标记。我还想将特殊字符作为标记包括在内。

char * cstr = new char [str.length()+1];
strcpy (cstr, str.c_str());

char * p = strtok (cstr," ");

while (p!=0)
{
whichType(p);
p = strtok(NULL," ,;=");
}

所以现在如果我打印出一个字符串的标记,例如 asd sdf qwe wer,sdf;wer 它将是

asd
sdf
qwe
wer
sdf
wer

我希望它看起来像

asd
sdf
qwe
wer
,
sdf
;
wer

任何帮助都会很棒。谢谢

最佳答案

您需要更大的灵 active 。 (此外,strtok 是一个糟糕的、容易出错的界面)。

这是一个灵活的算法,可以生成标记,将它们复制到输出迭代器。这意味着您可以使用它来填充您选择的容器,或将其直接打印到输出流(这就是我将用作演示的内容)。

行为在选项标志中指定:

enum tokenize_options
{
tokenize_skip_empty_tokens = 1 << 0,
tokenize_include_delimiters = 1 << 1,
tokenize_exclude_whitespace_delimiters = 1 << 2,
//
tokenize_options_none = 0,
tokenize_default_options = tokenize_skip_empty_tokens
| tokenize_exclude_whitespace_delimiters
| tokenize_include_delimiters,
};

不是我实际上如何提炼出您没有命名的额外要求,但您的示例暗示:您希望分隔符作为标记输出除非它们是空格 (' ')。这就是第三个选项的作用:tokenize_exclude_whitespace_delimiters

现在是真正的肉:

template <typename Input, typename Delimiters, typename Out>
Out tokenize(
Input const& input,
Delimiters const& delim,
Out out,
tokenize_options options = tokenize_default_options
)
{
// decode option flags
const bool includeDelim = options & tokenize_include_delimiters;
const bool excludeWsDelim = options & tokenize_exclude_whitespace_delimiters;
const bool skipEmpty = options & tokenize_skip_empty_tokens;

using namespace std;
string accum;

for(auto it = begin(input), last = end(input); it != last; ++it)
{
if (find(begin(delim), end(delim), *it) == end(delim))
{
accum += *it;
}
else
{
// output the token
if (!(skipEmpty && accum.empty()))
*out++ = accum; // optionally skip if `accum.empty()`?

// output the delimiter
bool isWhitespace = std::isspace(*it) || (*it == '\0');
if (includeDelim && !(excludeWsDelim && isWhitespace))
{
*out++ = { *it }; // dump the delimiter as a separate token
}

accum.clear();
}
}

if (!accum.empty())
*out++ = accum;

return out;
}

完整的演示是 Live on Ideone (default options) Live on Coliru (no options)

int main()
{
// let's print tokens to stdout
std::ostringstream oss;
std::ostream_iterator<std::string> out(oss, "\n");

tokenize("asd sdf qwe wer,sdf;wer", " ;,", out/*, tokenize_options_none*/);

std::cout << oss.str();
// that's all, folks
}

打印:

asd
sdf
qwe
wer
,
sdf
;
wer

关于c++ - strtok 如何还包括分隔符作为标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19036694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com