2013-12-08 38 views
0

我想解析一串1200首歌曲,我想每次找到'\ n'或我的barCount = 4時將我的barCount設置爲0。從我在網上找到的內容來看,\ n代表一個角色,但我不確定該如何處理這些信息......我怎麼才能找到它,然後做我需要做的事情?是否可以使用string :: find來檢測新的行字符?

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

你提供的代碼有什麼問題?它工作嗎?如果不是,問題是什麼? – ApproachingDarknessFish

+3

我認爲你需要在你已經找到的所有角色之後開始搜索。即'chartDataString.find(「\ n」,start)' –

+0

我不知道它在工作......因爲我處於while循環中,所以我希望它繼續通過,所以如果我們看到\ n ,barCount = 0,如果在我們看到的下一個字符上我想增加我的barCount ...但barCount沒有被調整 – Sarah

回答

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

這是一個有點冗長,但它試圖掰開所有不同的條件。希望這會有所幫助。

+0

非常感謝! – Sarah

相關問題