2012-03-24 60 views
0

我想匹配两个串彼此,而不在意三个条件:定义字符忽略同时匹配字符串C#

1-区分大小写(都应该不区分大小写):谁< =>谁

2-下划线:father_of < =>的父

3缺失空间:barackobama < =>布鲁克斯

因此,下面两个字符串应当彼此匹配

谁是fatherof barack_obama < =>谁是奥巴马的父亲

我不知道从哪里开始,我试图让两个字符串的排列,考虑下划线和缺少空格的这两种情况下,所以它会像

Who, is, fatherof, barack_obama 

who is, is fatherof, fatherof barack_obama, 
whois, isfatherof, fatherofbarack_obama, 
who_is, is_fatherof, fatherof_barack_obama, 

who is fatherof, is fatherof barack_obama 
whoisfatherof, isfatherofbarack_obama 
who_is_fatherof, is_fatherof_barack_obama 

who is fatherof barack_obama 
whoisfatherofbarack_obama 
who_is_fatherof_barack_obama 

这是很好的匹配奥巴马与barack_obama但反过来并不好,即使我能够在两者之间有undserscore分割字符串,我不能做到这一点与失踪空间

+3

您预期提出问题,而不是分配任务。 – 2012-03-24 20:24:37

+1

@HansPassant你会得到'我该怎么做?') – 2012-03-24 20:26:19

+1

嗯,这是一个合理的猜测,我猜。我猜不出为什么我们必须猜测。 – 2012-03-24 20:30:22

回答

6

也许会:

public static class StringExtensions 
{ 
    private string NormalizeText(string text) 
    { 
    return text..Replace("_","") 
       .Replace(" ","") 
       .Replace(",",""); 

    } 

    public static bool CustomEquals(this string instance, string otherString) 
    { 
    return NormalizeText(instance).Equals(NormalizeText(otherString), 
              StringComparison.CurrentCultureIgnoreCase); 
    } 
} 

所以

"Who is the fatherof barack_obama" 
"who IS the father of barack obama" 

比较喜欢(忽略大小写)

"Whoisthefatherofbarackobama" 
"whoISthefatherofbarackobama" 
+0

是的,这可能比利用正则表达式更可读。 +1 – dwerner 2012-03-24 20:30:07

+0

更新为使用OP(逗号)添加的新条件进行匹配。 – 2012-03-24 20:31:46

+1

功能在stackoverflow蠕变。我一直注意到这种趋势。问得很快,修改为答案开始进来。它是有道理的,使一个问题更好 - 但这种家庭作业PLZ GIMME代码的东西... – dwerner 2012-03-24 20:35:26

2

短一点的版本与用于去除字符的正则表达式:

public static class StringExtensions 
{ 
    public static bool CustomEquals(this string current, string other) 
    { 
     string pattern = @"[_\s,]"; 
     return String.Equals(
      Regex.Replace(current, pattern, String.Empty), 
      Regex.Replace(other, pattern, String.Empty), 
      StringComparison.CurrentCultureIgnoreCase); 
    } 
}