我想解析一个字符串并替换该字符串中的某些字符,我尝试使用分隔符,但它无法正常工作。
这是我要解析的字符串:
chartData = [T44E-7 | x |G-7 | x |
Bb^7 | x |Bh7 |E7#9 |A-7 | x |F#h7 | x |F-7 | x Q |C-7 | x |B7#9 | x Z Y{QC-7 | x |Ab^7 | x }
这是我想要的最终结果:
[T44E-7 | x |G-7 | x |
| Bb^7 | x |Bh7 |E7#9 |
|A-7 | x |F#h7 | x |
|F-7 | x Q |C-7 | x |
|B7#9 | x ||
|:QC-7 | x |Ab^7 | x :|
我还想将%,Z替换为||,{with |:和}替换为:|。
这是我的解析函数:
void parseChartData(string chartDataString){
string token;
if(!chartDataString.empty()){
chartData.clear();
chartData.append(chartDataString);
string delimiter = "|";
int pos = 0;
while ((pos = chartData.find(delimiter)) != pos) {
token = chartData.substr(0,pos);
cout << token << endl;
}
}
}
答案 0 :(得分:0)
我认为第一个解决方案是这个。
int occurrencies = 0; // number of "|" found
int curPos = 0;
int startPos = 0;
string delimiter = "|";
// find the next delimiter from the last one found, not from the beginning of chartData
while ((pos = chartData.find(delimiter, curPos)) != string::npos) {
curPos = pos+1;
occurrencies++;
// print something only if 4 delimiters have been found
if (occurrencies%4 == 0) {
// print the part from the last character printed to the last delimiter found
string part = chartData.substr(startPos,pos-startPos);
cout<<part<<endl;
// after printing, the last character printed become the beginning of the next token
startPos = pos+1;
}
}
// at the end print the remaining part of chartData
string lastPart = chartData.substr(startPos,string.size()-startPos);
cout<<lastPart<<endl;
应该有效