[英]Parsing strings in C++ by multiple delimiters
我有一個類似的字符串對象:
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()的實現將基於給定的定界符將一個字符串分成多個字符串。 這不是最有效的方法,但是可以帶來很多直觀的感覺。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.