I have a list of strings, which I want to find the start and end indices of their occurrence in a given string.
I want to find the longest common substring that is present in the original string and only print it.
Here is my code:
public static void Main(string[] args)
{
//This is my original string where I want to find the occurance of the longest common substring
string str = "will you consider the lic premium of my in-laws for tax exemption";
//Here are the substrings which I want to compare
List<string> subStringsToCompare = new List<string>
{
"Life Insurance Premium",
"lic",
"life insurance",
"life insurance policy",
"lic premium",
"insurance premium",
"insurance premium",
"premium"
};
foreach(var item in subStringsToCompare)
{
int start = str.IndexOf(item);
if(start != -1)
{
Console.WriteLine("Match found: '{0}' at {1} till {2} character position", item, start, start + item.Length);
}
}
}
The problem is I am getting 3 occurrences instead of one. I can't seem to figure out the condition where it gets the longest common matched substring from all substring to compare.
Output I am getting:
- Match found: 'lic' at 22 till 25 character position
- Match found: 'lic premium' at 22 till 33 character position
- Match found: 'premium' at 26 till 33 character position
Output expected:
- Match found: 'lic premium' at 22 till 33 character position