【问题标题】:C++: Splitting a string with multiple delimiters and keep the delimiters in the results?C ++:使用多个分隔符拆分字符串并将分隔符保留在结果中?
【发布时间】:2013-07-04 18:17:07
【问题描述】:

有没有一种好的方法可以通过多个分隔符拆分字符串(在 C 或 C++ 中),同时将分隔符保留为拆分字符串的一部分?我发现这样做的唯一方法是使用正则表达式,我宁愿不必为了做到这一点而引入另一个库? (我对字符串使用 STL,而不是使用 Boost)。

【问题讨论】:

  • 您希望分隔符在它前面的术语中还是在它后面的术语中? (例如CSV:this,is,an,example变成this,is,an,examplethis,is,an,example?)
  • 接下来,虽然没关系,但我只需要能够再次将它们组装回来。
  • 你可以使用 find_first_of() 和 substr() 来实现,但这不是一个调用...

标签: c++ c string stl


【解决方案1】:

没有正则表达式,虽然我不确定它是更快还是更慢:

vector<string> split(string& stringToSplit)
{
    vector<string> result;
    size_t pos = 0, lastPos = 0;
    while ((pos = stringToSplit.find_first_of(";,|", lastPos)) != string::npos)
    {
        result.push_back(stringToSplit.substr(lastPos, pos-lastPos+1));
        lastPos = pos+1;
    }
    result.push_back(stringToSplit.substr(lastPos));
    return result;
}

【讨论】:

    【解决方案2】:

    您可以使用前瞻来做到这一点。用表达式拆分:

    (?=,)
    

    对于逗号分隔符,并添加(可能在字符类中:[ ... ])要拆分的其他分隔符。

    所以,this,is,an,example 变为:this ,is ,an ,example(即分隔符与它后面的术语一起使用)

    否则,您将使用后视(意思是(?&lt;=,))来获得:this,is,an,example

    【讨论】:

      猜你喜欢
      • 2015-02-26
      • 1970-01-01
      • 2011-06-08
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多