是否可以使用string :: find来检测新的行字符?

时间:2013-12-08 22:29:08

标签: c++ string parsing

我正在尝试解析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;
    }
}

1 个答案:

答案 0 :(得分: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
    }
}

它有点冗长,但它试图打破所有不同的条件。希望这有帮助。