1

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

我的条目有名称“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.

        }
    }
}
4

3 回答 3

1

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

line = myReader.ReadLine();                                                     
if (line != null && line.IndexOf(x, StringComparison.CurrentCultureIgnoreCase) >= 0)
      Console.WriteLine(line);
于 2013-04-20T15:59:06.953 回答
1

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

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

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

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

而不是检查是否为空

于 2013-04-20T16:09:42.410 回答
0

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

于 2013-04-21T12:01:45.990 回答