【问题标题】:Search text file for user variable - Whats wrong with this code搜索用户变量的文本文件 - 此代码有什么问题
【发布时间】:2013-04-20 15:54:42
【问题描述】:

尝试根据用户变量条目从文本文件中读取

我的条目有“Big Fred”这个名字的变体(大写/小写)

代码运行,但我没有得到任何结果。

我笔记本电脑上的代码指向我已从下面的代码中删除的特定位置。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ReadTextFileWhile
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the name you wish to search for: ");                       //Prompt user for the name they wish to search for
            string x = Console.ReadLine();                                                      //assign the name the user inputs as their search parameter to the value of x
            StreamReader myReader = new StreamReader("C:/insert location here");      //Read the the text file at this location and assign to myReader
            string line = "";                                                                   //asssign 'nothing' to line.

            while (line != null)                                                                //while line in the text file is not null (empty)
            {
                line = myReader.ReadLine();                                                     //pass contents of myReader to line
                if (line != null && line == x)                                                  //if contents of line are not null and equal to the variable in x print to screen
                    Console.WriteLine(line);
            }

            myReader.Close();                                                                   //close myReader properly
            Console.ReadLine();                                                                 //Readline to keep console window open allowing a human to read output.

        }
    }
}

【问题讨论】:

标签: c# file variables search text


【解决方案1】:

尝试使用string.IndexOf 及其排除大小写差异的重载

line = myReader.ReadLine();                                                     
if (line != null && line.IndexOf(x, StringComparison.CurrentCultureIgnoreCase) >= 0)
      Console.WriteLine(line);

【讨论】:

  • 这已经解决了没有结果不显示的问题,但是它似乎显示了文本文件中的每一行,而不仅仅是包含用户变量的那些(里面有一个 Pete 和一个 Bruce用于测试目的的文件,它们会显示在结果中)。
  • 这很奇怪,除非你有不同类型的换行符。您可以尝试调试在 if 语句之前放置 Console.WriteLine(line) 的内容
  • 流氓;导致它将 if 语句视为空语句。史蒂夫干杯!
【解决方案2】:

您只想以不区分大小写的方式正确匹配字符串。您可以使用 .Equals

if (line.Equals(x,StringComparison.InvariantCultureIgnoreCase));

另一件事是:- 你可以使用

String.IsNullOrWhiteSpace(line) or String.IsNullOrEmpty(line) 

而不是检查是否为空

【讨论】:

    【解决方案3】:

    从文本文件中获取每一行的原因非常简单。您可能从网页或其他地方复制了文本内容。并且每一行都没有被换行符分隔,无论是 \n 还是 Environment.NewLine。因此,您需要打开文件并在每行之后按 Enter 键手动插入新行或从文件中读取所有测试并用点 [.] 分隔符拆分它,然后使用上面的代码单独处理它。我遇到了同样的问题,现在它工作正常。

    【讨论】:

      猜你喜欢
      • 2011-01-28
      • 1970-01-01
      • 2020-12-28
      • 2018-10-10
      • 2019-07-12
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多