C# - How to find the longest common parts of list of strings.

  • Thread starter Thread starter zydjohn
  • Start date Start date
Z

zydjohn

Guest
Hello:

I have the following code:

string header_item = "", trailer_item = "";
List<string> total_items = new List<string>();
total_items.Add("1,2,3,4,5,6,7,8");
total_items.Add("1,2,4,3,5,6,7,8");
total_items.Add("1,2,5,4,3,6,7,8");
total_items.Add("1,2,4,5,3,6,7,8");
total_items.Add("1,2,5,3,4,6,7,8");

header_item = "1,2";
trailer_item = "6,7,8";


I have a list of strings, as in total_items, I want to write a function to return the common parts. For example, in my above example, the first part of common “SubString” of all the string is header_item = "1,2"; and the last part of common “SubString” of all the string is trailer_item = "6,7,8".

If all the strings are the same in total_items, i.e: all the strings are "1,2,3,4,5,6,7,8"; then header_item = "1,2,3,4,5,6,7,8"; and trailer_item = "1,2,3,4,5,6,7,8". If there is no common “SubString”, i.e: all the strings in total_items are different, then header_item = "" and trailer_item = "". The length of the common “SubString” has to be the longest. For example, in my code above, even trailer_item = "7,8" is also a common “SubString” in total_items, but its length is only 3, yet trailer_item = "6,7,8" has the length of 5, so trailer_item = "6,7,8" is the answer.

I would like to do this using LINQ or something else, but I haven’t figured this out.

Thanks for advices.

Continue reading...
 
Back
Top