Home > Enterprise >  Compare two strings to find any duplicates
Compare two strings to find any duplicates

Time:03-16

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. The other is just a user input string, called 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. 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?

CodePudding user response:

You can try it with different ways,

Using 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,

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);

CodePudding user response:

Very similar to what Prasad did, except we ignore blank lines and use a case-insensitive comparison:

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"));
}
  • Related