通过多个分隔符解析C++中的字符串

Parsing strings in C++ by multiple delimiters

本文关键字:C++ 字符串 分隔符      更新时间:2023-10-16

我有一个字符串对象,如下所示:

string test = "
[3, 4, 8, 10, 10]n[12]n[12, 10,n 20]
"

并尝试将其解析为 3 个单独的数组,分别等于 [3, 4, 8, 10, 10]、[12] 和 [12,10, 20]。我之前已经将逗号分隔的整数解析为一个数组,但是我该如何解析这个数组。不幸的是,我拥有的数据可以在中间数组中换行,否则我会使用"getline"函数(将文件读取到字符串中时)并简单地忽略括号。

似乎我需要首先将每个数组放入由括号分隔的自己的字符串中,然后通过逗号消除将每个数组解析为整数数组。这行得通吗?

如果是这样,如何按括号将字符串拆分为以前未知数量的其他字符串?

您可以使用

流和std::getline(),因为std::getline()将分隔符作为参数:

int main()
{
    std::string test = "[3, 4, 8, 10, 10]n[12]n[12, 10,n 20]";
    // make data a stream (could be a std::ifstream)
    std::istringstream iss(test);
    // working vars
    std::string skip, item;
    // between square braces
    // skip to the opening '[' then getline item to the closing ']'
    while(std::getline(std::getline(iss, skip, '['), item, ']'))
    {
        // item = "3, 4, 8, 10, 10"
        // store numbers in a vector (not array)
        std::vector<int> v;
        // convert item to a stream
        std::istringstream iss(item);
        // separated by commas
        while(std::getline(iss, item, ','))
            v.push_back(std::stoi(item));
        // display the results
        std::cout << "list:" << 'n';
        for(auto i: v)
            std::cout << "t" << i << 'n';
    }
}

输出:

list:
    3
    4
    8
    10
    10
list:
    12
list:
    12
    10
    20

如果您已经将整个内容读入字符串,则以下内容应该有效:

#include <iostream>
#include <string>
using namespace std;
int main() {
  string test = "[3, 4, 8, 10, 10]n[12]n[12, 10,n 20]";
  size_t start = 0;  // first position in the string
  // find the first occurance of "]"
  size_t pos = test.find("]");
  while ( pos != string::npos ) {
    // move to position after "]"
    // so it is included in substring
    pos += 1;
    // create a substring
    string subStr = test.substr(start, pos-start);
    // remove newlines from new string
    size_t newLinePos = subStr.find("n");
    while ( newLinePos != string::npos ) {
      subStr.erase(newLinePos,1);
      newLinePos = subStr.find("n");
    }
   // here is the substring, like: [12, 10, 20]
    cout << "Substring: " << subStr << endl;
    // update start position for next substring
    start = pos;
    // find next occurrance of "]"
    pos = test.find("]", pos);
  }
}

解决此问题的一种方法是使用 explode() 函数。 explode() 的实现将根据给定的分隔符将字符串分成多个字符串。 这不是最有效的方法,但它可以带来很多直观的意义。

看:在 PHP 的 explode() 函数C++中是否有等效的函数?