[英]C# - Check if string contains characters of another string at the same order
[英]Find if string contains at least 2 characters similar to another? C#
我需要一種方法來檢查字符串是否包含一個或多個與另一個相似的字符。 我不想找到所有包含字母“ D”的字符串。 例如,如果我有一個字符串“ Christopher”,並且想查看“ Christopher”中是否包含“ Chris”,我希望返回它。 但是,如果我想查看字符串“ Christopher”中是否包含“ Candy”,就不要因為它有一個共同的“ C”而返回它。
我已經嘗試過.Contains()方法,但是不能給出2個或更多類似字符的規則,並且我曾考慮過使用正則表達式,但這可能會導致終止。 相似的字母必須彼此相鄰。
謝謝 :)
這將查找s1
每個2個字符的語法,並在s2
查找它。
string s1 = "Chrx";
string s2 = "Christopher";
IsMatchOn2Characters(s1, s2);
static bool IsMatchOn2Characters(string a, string b)
{
string s1 = a.ToLowerInvariant();
string s2 = b.ToLowerInvariant();
for (int i = 0; i < s1.Length - 1; i++)
{
if (s2.IndexOf(s1.Substring(i,2)) >= 0)
return true; // match
}
return false; // no match
}
這看起來很像是最長的常見子串問題 。 使用O(m * n)中的DP可以輕松解決此問題。
如果您不擔心性能並且真的不想實現此功能,則還可以使用蠻力解決方案,將s1的每個子字符串搜索到s2中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.