If StringOne
is:
Cat
Cat
Bird
Dog
How would I get 3
of three if StringTwo
is
Cat
Bird
public static void FindNumberOfSimilarStrings()
{
string[] var = StringOne();
foreach(string line in StringTwo())
{
foreach(string entry in var)
{
if (input.IndexOf(line, StringComparison.OrdinalIgnoreCase) >= 0)
{
Console.WriteLine(line);
instances++;
}
}
}
Note: The code above needs to be so that StringTwo can be expanded independently from the program. This means StringTwo
is actually a file whose data is obtained through this:
public static string[] StringTwo()
{
return File.ReadAllLines(path);
}
And StringOne
like this:
public static string[] StringOne()
{
return Program.textVariable.Split(' ');
}
The original string of text is "Cat cat bird dog" and as there is a split function it should be processed like this. I also want this to ignore case.
Cat
Cat
Bird
Dog
As long as there as a solution that permits this, it's fine.
UPDATE
Considering that you only want to know how many instances of a single string from the first collection happens within the second collection of strings.
var firstStrArray = new string[] { "Cat", "Cat", "Bird", "Dog" };
var secondStrArray = new string[] { "Cat", "Bird" };
var firstStrArrayGroups = firstStrArray.GroupBy(row => row.Trim()).Select(row => new { row.Key, Count = row.Count() }).ToList();
var secondStrArrayGroups = secondStrArray.GroupBy(row => row.Trim()).Select(row => new { row.Key, Count = row.Count() }).ToList();
foreach (var item in firstStrArrayGroups)
{
if (!secondStrArrayGroups.Any(row => row.Key.ToLower() == item.Key.ToLower()))
{
Console.WriteLine($"No Instance of => {item.Key} occured in second array.");
continue;
}
Console.WriteLine($"{secondStrArrayGroups.FirstOrDefault(row => row.Key.ToLower() == item.Key.ToLower()).Count} Instance of => {item.Key} occured in second array.");
}
Which result would be :
The last approach showed you how many instances of a string occurred within both collections, apologies for the misunderstanding.
I went a little overboard and added a few details such as Trim()
and ToLower()
if they do not match your business, remove them.