我想比较两个字符串,忽略几个字(比如三个)。
就像我比较这两个字符串一样:
"Hello! My name is Alex Jolig. Its nice to meet you."
"My name is Alex. Nice to meet you."
我应该得到True
的结果。
有没有办法做到这一点?
答案 0 :(得分:0)
我没有想到任何内置的内容,但我认为您可以使用分隔符(''在您的情况下)来标记两个字符串。标点符号(在您的情况下为!&。)。
一旦两个字符串在订购的代币中被分解,您可以根据您的要求在各个代币之间进行比较。
答案 1 :(得分:0)
你可以将字符串拆分成单词并像这样比较它们;
private bool compareStrings()
{
string stringLeft = "Hello! My name is Alex Jolig. Its nice to meet you.";
string stringRight = "My name is Alex. Nice to meet you.";
List<string> liLeft = stringLeft.Split(' ').ToList();
List<string> liRight = stringRight.Split(' ').ToList();
double totalWordCount = liLeft.Count();
double matchingWordCount = 0;
foreach (var item in liLeft)
{
if(liRight.Contains(item)){
matchingWordCount ++;
}
}
//return bool based on percentage of matching words
return ((matchingWordCount / totalWordCount) * 100) >= 50;
}
这将根据匹配单词的百分比返回一个布尔值,您可能希望使用正则表达式或类似方法替换某些格式字符以获得更准确的结果。
答案 2 :(得分:0)
在codeproject中有一篇关于模糊字符串匹配与编辑距离的文章 您可以扩展这个想法以满足您的要求。它使用Levenshtein的编辑距离作为模糊字符串匹配。
http://www.codeproject.com/Articles/162790/Fuzzy-String-Matching-with-Edit-Distance
答案 3 :(得分:0)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var string1 = "Hi thar im a string";
var string2 = "Hi thar im a string";
var string3 = "Hi thar im a similar string";
var string4 = "im a really different string";
var string5 = "Hi thar im a string but have many different words";
Console.WriteLine(StringComparo(string1, string2));
Console.WriteLine(StringComparo(string1, string3));
Console.WriteLine(StringComparo(string1, string4));
Console.WriteLine(StringComparo(string1, string5));
Console.ReadLine();
}
public static bool StringComparo(string str1, string str2, int diffCounterLimiter = 3)
{
var counter = 0;
var arr1 = str1.Split(' ');
var arr2 = str2.Split(' ');
while (counter <= diffCounterLimiter)
{
TreeNode bestResult = null;
for (int i = 0; i < arr1.Length; i++)
{
for (int j = 0; j < arr2.Length; j++)
{
var result = new TreeNode() { arr1Index = i, arr2Index = j };
if (string.Equals(arr1[i], arr2[j]) && (bestResult == null || bestResult.diff < result.diff))
{
bestResult = result;
}
}
}
// no result found
if(bestResult == null)
{
// any left over words plus current counter
return arr1.Length + arr2.Length + counter <= diffCounterLimiter;
}
counter += bestResult.diff;
arr1 = arr1.Where((val, idx) => idx != bestResult.arr1Index).ToArray();
arr2 = arr2.Where((val, idx) => idx != bestResult.arr2Index).ToArray();
}
return false;
}
}
public class TreeNode
{
public int arr1Index;
public int arr2Index;
public int diff => Math.Abs(arr1Index - arr2Index);
}
}
我试图实现一个树搜索(我知道它不是一个真正的搜索树,我可能会稍微写一下)。
本质上,它在每个字符串中找到最接近的匹配元素。在3个差异的限制下,它删除匹配的元素,添加差异并重复。希望它有所帮助。