Irfan Wattoo Irfan Wattoo - 1 month ago 13
C# Question

string comparison, return most similiar

Search substrings from a string and get a substring that matches the most!

string [] allModels = { "Galaxy", "S3", "Galaxy S3" };
string title = "Samasung galaxy s3 is for sale";
string[] title_array = title.Split(' ');
string model = "";
foreach(var tit in title_array)
{
foreach(var mod in allModels)
{
if (mod.Equals(tit, StringComparison.OrdinalIgnoreCase))
{
model = mod;
}
}
}


The model selected is
Galaxy
but I need
Galaxy S3
(i.e, most similar). How can I get
Galaxy S3
.

Should I use
Array.FindAll(target)
method?

Update:

By
most similar
I mean the substring (model) that matches the most from string(title)

e.g, in
galaxy Samasung s3 is for sale
the model should be
galaxy s3
(according to above
allModels
array)

L.B L.B
Answer

Most similar? don't have to be Search substrings from a string and get a substring that matches the most! I'll presume you want a longest match...

string[] allModels = { "Galaxy", "S3", "Galaxy S3" };
string title = "Samasung galaxy s3 is for sale";

var mod = allModels.OrderByDescending(x => x.Length)
          .FirstOrDefault(x => title.IndexOf(x,StringComparison.OrdinalIgnoreCase)>=0);
Comments