[英]String cannot contain any part of another string .NET 2.0
我正在尋找一種簡單的方法來識別一個字符串是否包含另一個字符串的任何部分(例如,正則表達式,我不知道的內置函數等)。 例如:
string a = "unicorn";
string b = "cornholio";
string c = "ornament";
string d = "elephant";
if (a <comparison> b)
{
// match found ("corn" from 'unicorn' matched "corn" from 'cornholio')
}
if (a <comparison> c)
{
// match found ("orn" from 'unicorn' matched "orn" from 'ornament')
}
if (a <comparison> d)
{
// this will not match
}
諸如if (a.ContainsAnyPartOf(b))
類的東西實在是太令人希望了。
另外,我只能訪問.NET 2.0。
提前致謝!
此方法應該起作用。 您需要為可能匹配的“零件”指定最小長度。 我假設您要查找至少2的值,但是您可以根據需要將其設置為高或低。 注意:不包括錯誤檢查。
public static bool ContainsPartOf(string s1, string s2, int minsize)
{
for (int i = 0; i <= s2.Length - minsize; i++)
{
if (s1.Contains(s2.Substring(i, minsize)))
return true;
}
return false;
}
我認為您正在尋找最長公共子字符串的此實現?
根據我對問題的理解,您最好的選擇是計算Levenshtein (或相關值)距離並將其與閾值進行比較。
您的要求有點含糊。
您需要為匹配定義一個最小長度...但是當您弄清楚該部分時,實施算法應該不會太困難。
我建議將字符串分解為字符數組,然后使用尾部遞歸來查找各部分的匹配項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.