gpt4 book ai didi

c# - 将用户输入与文本文件中的字符串列表进行比较

转载 作者:行者123 更新时间:2023-11-30 22:57:29 24 4
gpt4 key购买 nike

我有一个文本文件,上面列出了这些单词

Laptop
Laser
Macho
Sam
Samantha
Mulder
Microphone
Aardvark

我想要做的是让用户输入一个词,控制台基本上会响应我们有你的话或我们没有你的话。到目前为止,这是我的代码:

TextReader file = new StreamReader("Files/Exercise_Files/Words.txt");

Console.WriteLine("Welcome to FindWord");
string wordInput;
Console.WriteLine("Type in a word so we can try and find it: ");
wordInput = Console.ReadLine();

string sLine = file.ReadToEnd();
if (String.Compare(wordInput, sLine, true) == 0)
{
Console.WriteLine("We have found your word!");
}
else
{
Console.WriteLine("We have not found your word");
}

file.Dispose();

我已经尝试做几个版本来解决这个问题,其中一个包括添加一个 for-each 循环,但这让我很困惑。我不是 100% 确定何时使用 for-each 循环。我还希望字符串比较不区分大小写,但无论我输入什么,我现在的代码总是会说找不到单词。

最佳答案

您可以使用 File.ReadAllLines()方法将文件行读入数组,然后是 Linq 扩展方法 Contains确定该列表中是否存在单词(您可以进行不区分大小写的搜索):

static void Main(string[] args)
{
var filePath = @"c:\temp\temp.txt";
var words = File.ReadAllLines(filePath);

Console.Write("Enter a search term: ");
var searchTerm = Console.ReadLine();

if (words.Contains(searchTerm, StringComparer.OrdinalIgnoreCase))
{
Console.WriteLine("We have your word!");
}
else
{
Console.WriteLine("We do not have your word");
}

Console.ReadKey();
}

关于c# - 将用户输入与文本文件中的字符串列表进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53618804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com