2016-08-25 72 views
2

我一直在試圖做出某種消息解析器,只獲取我發送的消息。例如,如果我有消息這樣的:消息解析器C#

Viktor Bale (11 aug. 2016 13:20:56): 
Hi! How are you? 

Not Viktor Bale (11 aug. 2016 13:20:56): 
Hi! Good! And you? 

Viktor Bale (11 aug. 2016 13:20:56): 
Me too! And this message has 
Two lines! 

Not Viktor Bale (11 aug. 2016 13:20:56): 
And this doesn't matter! 

我需要寫Viktor Bale 這裏只是消息的代碼,那我tryed:

for (int i = 0; i < wordsList.Count; i++) 
{ 
    if (wordsList[i].StartsWith(defaultName)) 
    { 
     while (!wordsList[i].StartsWith(dialName)) 
     { 
      messages.Add(wordsList[i]); 
     } 
    }  
} 

wordsList是我的郵件,從收到的名單txt文件並通過ReadAllLines 讀取上面的消息就是列表。

​​是我的名字,dialName是我的對話者的名字。

但是,當我啓動它,我的應用程序簡單地凍結。我應該怎麼做?

+4

你永遠不會在你的'while'循環增量'i'。所以如果它是真的,那麼這個循環會永遠運行。或..直到您無法在消息列表中添加更多項目 – MAV

+0

您應該調試您的代碼。比如果你仍然無法找到你的無限循環[編輯]後與[mcve] –

回答

2

您忘記增加i

for (int i = 0; i < wordsList.Count; i++) 
{ 
    if (wordsList[i].StartsWith(defaultName)) 
    { 
     while (i < worldList.Count && !wordsList[i].StartsWith(dialName)) 
     { 
      messages.Add(wordsList[i++]); 
     } 
    }  
} 

編輯:增加了一個安全邊界檢查。

+0

謝謝,那爲我工作 – Viktor

0

爲了避免無休止的while循環,使用此代碼來代替:

for (int i = 0; i < wordsList.Count; i++) 
{ 
    if (wordsList[i].StartsWith(defaultName)) 
    { 
     if (!wordsList[i].StartsWith(dialName)) 
     { 
     messages.Add(wordsList[i]); 
     } 
    }  
} 

OR

你可以用更簡單的東西來實現所需的行爲:

foreach (var word in wordsList) 
{ 
    if (word.StartsWith(defaultName)) 
    { 
     messages.Add(word); 
    }  
} 

希望它有助於

+1

不是每一行都以該人的名字開頭,只有「標題」行。該解決方案不適用於給定的輸入。 –

0

while循環永遠不會結束。

也許你的意思是這樣的?我已經整理好你的代碼並簡化了。

foreach (var words in wordsList) 
{ 
    if (words.StartsWith(defaultName) && !words.StartsWith(dialName)) 
    { 
    messages.Add(wordsList[i]); 
    } 
} 
+1

不是每一行都以該人的姓名開頭,只有「標題」行。該解決方案不適用於給定的輸入。 –

0

假設每行都以發送者的名字開頭,並且消息不包含換行符,那麼您應該可以使用linq選擇您的消息。 例如

var myMessages = wordsList.Where(x => x.StartsWith(defaultName)) 

應用程序崩潰在您的while循環中,它只是簡單地評估條件無窮大,但從不做任何事情來改變它。

0

這裏是做這樣的選擇:

public static string ExtractSenderName(string line) { 
    var i = line.IndexOf('('); 
    if (i == -1) 
     return string.Empty; 

    return line.Substring(0, i).Trim(); 
} 

public static void Main (string[] args) { 

    var messages = new List<string>(); 
    for (int i = 0; i < wordsList.Length; i++) 
    { 
     if (ExtractSenderName(wordsList[i]) == defaultName) { 
      messages.Add(wordsList[++i]); 
     } 
    } 

    foreach (var x in messages) { 
     Console.WriteLine(x); 
    } 
} 

這裏是demo