我想要解析一个字符串并替换该字符串中的某些字符,我尝试使用分隔符,但它不能正常工作。
这是我想要解析的字符串:
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 :|我还想用%替换x,用||替换Z,用|:替换{,用:|替换}。
下面是我拥有的一个解析函数:
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;
}
}
}发布于 2013-12-10 03:03:50
我认为第一个解决方案是这个。
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;它应该是可行的
https://stackoverflow.com/questions/20477980
复制相似问题