【问题标题】:string.Split() and an if statementstring.Split() 和 if 语句
【发布时间】:2012-09-05 20:33:15
【问题描述】:

我有一个文本文件,我用 \n 拆分它。

文本文件(测试)读取

1
2
3
4

现在是令人困惑的部分。

代码

string test = System.IO.File.ReadAllText(@"C:\Custom tests\"+testselect.Text+".txt");

string[] check = test.Split('\n');

if (check[0] == "1")
{
     label.Text = "whatever";
}

这不起作用。标签保持默认值。但是,如果我:

label.Text = check[0];

标签显示一个 1。

我不明白,请帮忙。

【问题讨论】:

  • 您的文件很可能是 Windows 文本文件,在这种情况下,行是“\r\n”而不仅仅是“\n”,因此数组中的每个字符串可能是“1\ r" 等。见 Reed 的回答。
  • 我猜它甚至可能不会被拆分

标签: c# string-split


【解决方案1】:

首先 - 你应该能够只使用 File.ReadAllLines 而不是阅读文本和拆分....

您可能需要修剪结果。如果行上有多余的空格,则条件可能会失败。尝试使用:

if (check[0].Trim() == "1")
{

这将剪掉任何空白,这将使您的条件成功。

您还可以在调试器中设置断点并检查值。这将帮助您更好地诊断问题。

【讨论】:

    【解决方案2】:

    我认为您应该使用 Environment.NewLine。不同的操作系统使用不同的换行符。

    What is the universal newline for all operating systems? (LF and CR)

    【讨论】:

      【解决方案3】:

      你只是在比较数字吗?需要检查大小写和空格..

      string.Equals(check[0].Trim(), "some value", StringComparison.OrdinalIgnoreCase);
      

      【讨论】:

        【解决方案4】:

        你可以使用这样的东西:

        如果有,请删除退货

        string[] check = test.Replace("\r", "").Split('\n');
        
                if(check[0] == "1")
        

        或用换行符分割并取出数组中的字符并检查。

        string[] check = test.Split('\n');
        
                if(check[0][0] == '1')
        

        我会使用选项二。

        编辑:

        或类似的东西,但它有点 OTT,你会得到所有的\r\n

         char[] check = test.SplitMeUp();
        
                if(check[0] == '1')
        
        
         static class Extensions
        {
            public static char[] SplitMeUp(this string str)
            {
                char[] chars = new char[str.Length];
                for (int i = 0; i < chars.Length; i++)
                    chars[i] = str[i];
        
                return chars;
            }
        }
        

        编辑:

        过滤掉特定字符的其他方法

        public static char[] SplitMeUp(this string str, char[] filterChars = null)
            {
                List<Char> chars = new List<char>();
                for (int i = 0; i < str.Length; i++)
                {
                    if(filterChars != null && filterChars.Length > 0 && filterChars.Contains(str[i]))
                            continue; 
        
                    chars.Add(str[i]);
                }
        
                return chars.ToArray();
            }
        

        并像使用它

        char[] check = test.SplitMeUp(new char[] {'\r', '\n'});
        
                if(check[0] == '1')
        

        它会忽略所有这些 \r\n 并将所有内容分开。

        【讨论】:

          猜你喜欢
          • 2016-03-02
          • 2016-02-29
          • 1970-01-01
          • 2014-02-15
          • 2013-03-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-02-22
          相关资源
          最近更新 更多