gpt4 book ai didi

c++ - C++ 中的字符串标记化,包括定界符

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:20:22 26 4
gpt4 key购买 nike

我有以下形式的字符串a = x + yabc = xyz + 56 + 5f(p)

我需要的是标记字符串,以便我读取每个 operatoroperand所以对于 a = x + y token 返回应该是 a,=,x,+,y 并且在 abc=xyz+5 的情况下它应该返回 abc,=,xyz,+,5。请注意,operatoroperands

之间可能有也可能没有空格

这是我试过的

void tokenize(std::vector<std::string>& tokens, const char* input, const char* delimiters) {
const char* s = input;
const char* e = s;
while (*e != 0) {
e = s;
while (*e != 0 && strchr(delimiters, *e) == 0) {
++e;
}
if ( *e != ' ' && strchr(delimiters, *e) != 0 ){
std::string op = "";
op += *e;
tokens.push_back(op);
}
if (e - s > 0) {
tokens.push_back(std::string(s,e - s));
}
s = e + 1;
}
}

最佳答案

您可以使用此实现。第一个参数是要标记化的 std::string,第二个参数是要使用的分隔符。它返回标记化的字符串 vector 。非常简单但高效。

vector<string> tokenizeString(const string& str, const string& delimiters)
{
vector<string> tokens;
// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
string::size_type pos = str.find_first_of(delimiters, lastPos);

while (string::npos != pos || string::npos != lastPos)
{ // Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
return tokens;
}

关于c++ - C++ 中的字符串标记化,包括定界符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9823263/

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