简体   繁体   English

比较两个字符串以查找重复项

[英]Compare two strings to find any duplicates

I really cannot find the answer to this question and it is driving me mental.我真的找不到这个问题的答案,这让我精神错乱。 I have two strings, one is a text file that is read into a string called logfile.我有两个字符串,一个是一个文本文件,它被读入一个名为 logfile 的字符串。 The other is just a user input string, called text1.另一个只是用户输入的字符串,称为 text1。 Eventually it's just going to be a guessing game with hints, but I can't figure out how to compare these two for equality.最终它只是一个有提示的猜谜游戏,但我不知道如何比较这两者是否相等。

string LOG_PATH = "E:\\Users\\start.txt";
string logfile = File.ReadAllText(LOG_PATH);
string text1 = "";
text1 = Console.ReadLine();

if (logfile.Contains(text1))
{
    Console.WriteLine("found");
}
else
{
    Console.WriteLine("not found");
}

This code works fine when there is only one word in the text file and matches.当文本文件中只有一个单词并且匹配时,这段代码工作正常。 If the text file only contains the word "Mostly" and the user entered mostly and a bunch of other words, the console prints found.如果文本文件只包含单词“Mostly”并且用户输入了 mostly 和一堆其他单词,则控制台会打印 found。 But if the text file has mostly and a bunch of other random words, say "Mostly cloudy today", the console prints not found.但是,如果文本文件包含大部分内容和一堆其他随机词,例如“今天多云”,控制台会打印未找到。 Is it possible to match to strings for ANY duplicates at all?是否有可能完全匹配任何重复项的字符串?

You can try it with different ways,你可以尝试不同的方式,

Using Except() ,使用Except()

var wordsFromFile = File.ReadAllText(LOG_PATH).Split(' ').ToList();
var inputWords = Console.ReadLine().Split(' ').ToList();

Console.WriteLine(wordsFromFile.Except(inputWords).Any() ? "Found" : "Not Found");

Similar way using foreach() loop,使用foreach()循环的类似方式,

var wordsFromFile = File.ReadAllText(LOG_PATH).Split(' ').ToList();
var inputWords = Console.ReadLine();
string result = "Not Found";

foreach(var word in inputWords)
{
      if(wordsFromFile.Contains(word))
      {
          result = "Found";
          break
      }
}
Console.WriteLine(result);

Very similar to what Prasad did, except we ignore blank lines and use a case-insensitive comparison:与 Prasad 所做的非常相似,除了我们忽略空行并使用不区分大小写的比较:

string LOG_PATH = @"E:\Users\start.txt";
List<String> logfileWords = new List<String>();
foreach (String line in File.ReadLines(LOG_PATH))
{
    logfileWords.AddRange(line.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
}

Console.Write("Words to search for (separated by spaces): ");
String[] inputs = Console.ReadLine().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine("Inputs:");
foreach(String input in inputs)
{
    Console.WriteLine(input + " ==> " + (logfileWords.Any(w => w.Equals(input, StringComparison.InvariantCultureIgnoreCase)) ? "found" : "not found"));
}

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

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