简体   繁体   English

字符串比较,返回最相似

[英]string comparison, return most similar

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 (ie, most similar). 选择的型号是Galaxy但我需要Galaxy S3 (即最相似的)。 How can I get Galaxy S3 . 如何获得Galaxy S3

Should I use Array.FindAll(target) method? 我应该使用Array.FindAll(target)方法吗?

Update: 更新:

By most similar I mean the substring (model) that matches the most from string(title) most similar意思是,子字符串(模型)与string(title)的匹配程度最高

eg, in galaxy Samasung s3 is for sale the model should be galaxy s3 (according to above allModels array) 例如,在galaxy Samasung s3 is for sale该型号应为galaxy s3 (根据上述所有allModels数组)

Most similar? don't have to be Search substrings from a string and get a substring that matches the most! 不必是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);

Here is a way to find the model containing the most words of the title. 这是查找包含标题最多单词的模型的方法。

var allModelsList = new List<String>(allModels);
var titles = new List<String>(title_array);
allModelsList.OrderByDescending(model => titles.Where(title => title.Equals(model, StringComparison.OrdinalIgnoreCase)).Count()).FirstOrDefault();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM