繁体   English   中英

C#StreamReader,在新行拆分问题

[英]C# StreamReader, trouble splitting at new line

我有一个全局字符串变量-“ word”。

    string word = "";
    List<Label> labels = new List<Label>();
    int amount = 0;

然后通过解析文本文档(用新行分隔)在以下两个函数中定义/分配该单词

    void MakeLabels()
    {
        word = GetRandomWord();
        char[] chars = word.ToCharArray();
        ...
    }


    string GetRandomWord()
    {

        System.IO.StreamReader myFile = new System.IO.StreamReader(...);
        string myString = myFile.ReadToEnd();
        string[] words = myString.Split('\n');
        Random ran = new Random();
        return words[ran.Next(0, words.Length - 1)];
    }

最后,是一个事件,该事件针对“ word”变量验证了文本框的内容。

    private void button2_Click(object sender, EventArgs e)
    {
        if (textBox2.Text == word)
        {
            MessageBox.Show(...);
        }
        else
        {
            MessageBox.Show(...);
            textBox2.Text = "";
            textBox1.Focus();
            Reset();
        }

我遇到的问题是,即使textBox2等效于“ word”,我也会收到与else语句相关的MessageBox。 我认为这与“ \\ n”中携带的“ word”变量有关; 表示textBox2.Text = apple和word = apple \\ n,因此两个变量不相等。 有什么建议么?

如果确定问题出在字符串末尾的换行符,则应查看String.Trim()方法。

1)Windows环境中的换行符是\\ r \\ n,而不是\\ n。 在\\ n上分割不足。
2)与建议相反,您不能简单地调用someString.Split(Environment.NewLine)。

没有简单地采用字符串的重载。 您可以调用someString.Split(Environment.NewLine.ToCharArray()),但还需要考虑其他一些问题。 假设我们有一个输入,字符串test =“ test1 \\ r \\ ntest2”。 如果调用test.Split('\\ n'),则结果数组将包含两个元素:array [0]将为“ test1 \\ r”,而array [1]将为“ test2” ...

但是,如果调用test.Split(Environment.NewLine.ToCharArray()),则会得到一个包含三个元素的数组:array [0]将为“ test1”,array [1]将为“”,array [2 ]将是“ test2” ...编辑添加:您可以通过调用test.Split(new string [] {Environment.NewLine},StringSplitOptions.None来解决该问题。

3)正如一个人所建议的那样,调用string.Trim()将删除\\ r。 因此,可以将返回单词[ran.Next(0,words.Length-1)]更改为返回单词[ran.Next(0,words.Length-1)]。Trim()以消除\\ r而无需进行更改到您当前的拆分代码。

使用如下内容

string[] parseStr = myTest.Split(new string[]{Environment.NewLine},StringSplitOptions.None);

CRLF在C#中解析蓝调

 string GetRandomWord()
  {

    string[] linse=  System .IO.File .ReadAllLines (......) ;
      string mlines = "";
        foreach (string line in linse)
          {
             if (line.Trim() != "")
                if(mlines=="")
                    mlines = line;
                else 
                mlines = mlines +"\n"+ line;
          }
        string[] words = mlines. Split('\n');

 Random ran = new Random();
    return words[ran.Next(0, words.Length - 1)];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM