【问题标题】:How to parse a string and replace certain characters of a string?如何解析字符串并替换字符串的某些字符?
【发布时间】:2013-12-09 18:32:20
【问题描述】:

我想解析一个字符串并替换该字符串中的某些字符我尝试使用分隔符但它不能正常工作。

这是我要解析的字符串:

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;
         }
    }
}

【问题讨论】:

  • 问题是什么?
  • 如何解析一个字符串,所以我每行只能显示 4 个条形

标签: c++ string parsing


【解决方案1】:

我认为的第一个解决方案是这个。

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;

它应该可以工作

【讨论】:

  • 只需更改“curPos = pos;”在“curPos = pos+1;”中。 infine 循环是因为它总是找到相同的字符。 “startPos = pos”也是一样,变成“startPos = pos+1”。
猜你喜欢
  • 2023-03-04
  • 2018-08-23
  • 2012-03-30
  • 2013-07-09
  • 2012-01-22
  • 2014-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多