【问题标题】:C++ Breaking up a string using multiple delimiters [duplicate]C ++使用多个分隔符分解字符串[重复]
【发布时间】:2012-10-26 01:53:21
【问题描述】:

可能重复:
Split a string into words by multiple delimiters in C++

我目前正在尝试读取一个文件,其中每一行都有不同的制表符和空格分隔需要插入二叉树的关键属性。

我的问题是:如何仅使用 STL 使用多个分隔符拆分一行?在一天的大部分时间里,我一直在试图解决这个问题,但无济于事。

非常感谢任何建议。

【问题讨论】:

标签: c++


【解决方案1】:

使用std::string::find_first_of

vector<string> bits;
size_t pos = 0;
size_t newpos;
while(pos != string::npos) {
    newpos = str.find_first_of(" \t", pos);
    bits.push_back(str.substr(pos, newpos-pos));
    if(pos != string::npos)
        pos++;
}

【讨论】:

  • 如果第一个字符是其中之一怎么办?也许从 -1 开始 pos,或者在循环之外进行初始搜索?
  • 已修复,感谢您的评论。
【解决方案2】:

使用string::find_first_of() [1]

int main ()
{
  string str("Replace the vowels in this sentence by asterisks.");
  size_t found;

  found = str.find_first_of("aeiou");
  while (found != string::npos) {
    str[found]='*';
    found=str.find_first_of("aeiou", found + 1);
  }

  cout << str << endl;

  return 0;
}

【讨论】:

    猜你喜欢
    • 2018-08-18
    • 2022-01-13
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 2020-04-17
    • 2011-06-27
    相关资源
    最近更新 更多