我正在尝试解析一个由1200首歌曲组成的字符串,每次找到'\n'或barCount=4时,我都想将我的barCount设置为0。根据我在网上发现的,\n代表一个字符,但我不确定该如何处理这些信息。。。我怎样才能找到它,然后做我需要做的事情?
int barCount = 0;
size_t start = 0;
size_t n = 0;
int charCount = 0;
while((start = chartDataString.find(" |", start)) != string::npos){
++barCount;
start+=2;
charCount++;
//if(barCount == 3){// || chartDataString.find("]")){
if(chartDataString.find("n") !=string::npos){
barCount = 0;
}
else if(barCount == 4 || chartDataString[charCount] == ']') {
chartDataString.insert(start, "n");
barCount = 0;
}
}
查看您的代码,我怀疑我理解您现在要做的事情。让我看看我是否明白了:
- 字符串中的每个歌曲标题/唱片最多由四个用竖条分隔的字段组成
- 记录可能会提前用右括号或换行符终止
- 如果它没有以换行符结束,请插入一个换行符
以下可能会做得更好:
size_t curr_pos = 0, next_bar, next_nl, next_brk;
int bar_count = 0;
while (true)
{
next_bar = chartDataString.find(" |", curr_pos);
next_nl = chartDataString.find("n", curr_pos);
next_brk = chartDataString.find("]", curr_pos);
if (next_bar == string::npos &&
next_nl == string::npos &&
next_brk == string::npos)
break;
// Is a newline the next thing we'll encounter?
if (next_nl < next_bar && next_nl < next_brk)
{
curr_pos = next_nl + 1; // skip past newline
bar_count = 0; // reset bar count
}
// Is a vertical bar the next thing we'll encounter?
if (next_bar < next_nl && next_bar < next_brk)
{
bar_count++;
curr_pos = next_bar + 2; // skip past vertical bar
}
// Is a right-bracket the next thing we'll encounter?
if (next_brk < next_bar && next_brk < next_nl)
{
bar_count = 4; // fake like we've seen all 4 bars
curr_pos = next_brk + 1; // skip past bracket
}
// Have we seen 4 vertical bars or a right bracket?
if (bar_count == 4)
{
bar_count = 0;
chartDataString.insert("n", curr_pos);
curr_pos += 1; // skip the newline we just inserted
}
}
它有点冗长,但它试图打破所有不同的条件。希望这能有所帮助。