首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何解析字符串并替换字符串中的某些字符?

如何解析字符串并替换字符串中的某些字符?
EN

Stack Overflow用户
提问于 2013-12-10 02:32:21
回答 1查看 144关注 0票数 0

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

这是我想要解析的字符串:

代码语言:javascript
复制
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  }

这就是我想要的最终结果:

代码语言:javascript
复制
[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,用|:替换{,用:|替换}。

下面是我拥有的一个解析函数:

代码语言:javascript
复制
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;
         }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2013-12-10 03:03:50

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

代码语言:javascript
复制
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;

它应该是可行的

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20477980

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档