【发布时间】:2015-09-18 02:35:18
【问题描述】:
我需要在 C++ 中创建字符串解析器。我尝试使用
vector<string> Tokenize(const string& strInput, const string& strDelims)
{
vector<string> vS;
string strOne = strInput;
string delimiters = strDelims;
int startpos = 0;
int pos = strOne.find_first_of(delimiters, startpos);
while (string::npos != pos || string::npos != startpos)
{
if(strOne.substr(startpos, pos - startpos) != "")
vS.push_back(strOne.substr(startpos, pos - startpos));
// if delimiter is a new line (\n) then add new line
if(strOne.substr(pos, 1) == "\n")
vS.push_back("\\n");
// else if the delimiter is not a space
else if (strOne.substr(pos, 1) != " ")
vS.push_back(strOne.substr(pos, 1));
if( string::npos == strOne.find_first_not_of(delimiters, pos) )
startpos = strOne.find_first_not_of(delimiters, pos);
else
startpos = pos + 1;
pos = strOne.find_first_of(delimiters, startpos);
}
return vS;
}
这适用于 2X+7cos(3Y)
(tokenizer("2X+7cos(3Y)","+-/^() \t");)
但给出 2X 的运行时错误
我需要非 Boost 解决方案。
我尝试使用C++ String Toolkit (StrTk) Tokenizer
std::vector<std::string> results;
strtk::split(delimiter, source,
strtk::range_to_type_back_inserter(results),
strtk::tokenize_options::include_all_delimiters);
return results;
但它不会将令牌作为单独的字符串。
例如:如果我将输入设为 2X+3Y
输出向量包含
2X+
3 年
【问题讨论】:
-
大概你需要保护
pos = str.find_first_of(delimiters, lastPos)免受lastPos是npos的情况。 -
如果您要使用非标准库(表面上是this)显示代码,您应该在问题中命名,提供链接,并考虑在您的问题中添加相关标签。
-
我添加了 strtk 是因为该解决方案无法解决我的问题。现在将添加链接