2016-08-25 73 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