确定HashSet <string>是否包含不同的套接字符串</string>

时间:2013-04-29 05:39:08

标签: c# string hashset similarity casing

我有很多字符串,包括许多重复字符串。重要的是所有重复具有相同的外壳。所以这个集合将无法通过测试:

String[] strings = new String[] { "a", "A", "b", "C", "b" };

....但是这个测试会通过:

String[] strings = new String[] { "A", "A", "b", "C", "b" };

当我遍历strings中的每个字符串时,我的程序如何看到Aa的不区分大小写的副本(因此失败),但允许重复{ {1}}通过?

3 个答案:

答案 0 :(得分:3)

一种简单的方法是创建两个集合 - 一个使用不区分大小写的字符串比较器,一个使用区分大小写的集合。 (我不清楚你是否想要一个文化敏感的字符串,或者在哪种文化中。)

构造之后,如果两个集合具有不同的大小(Count),那么必须有一些元素通过不区分大小写的比较相等,但不等于区分大小写的比较。

类似于:

public static bool AllDuplicatesSameCase(IEnumerable<string> input)
{
    var sensitive = new HashSet<String>(input, StringComparer.InvariantCulture);
    var insensitive = new HashSet<String>(input, 
          StringComparer.InvariantCultureIgnoreCase);
    return sensitive.Count == insensitive.Count;
}

答案 1 :(得分:0)

您可以明确检查每个条目。

static bool DuplicatesHaveSameCasing(string[] strings)
{
  for (int i = 0; i < strings.Length; ++i)
  {
    for (int j = i + 1; j < strings.Length; ++j)
    {
      if (string.Equals(strings[i], strings[j], StringComparison.OrdinalIgnoreCase)
        && strings[i] != strings[j])
      {
        return false;
      }
    }
  }
  return true;
}

评论:我选择使用序数比较。请注意,!=运算符使用序数和区分大小写的比较。将此变为某种依赖文化的比较是相当微不足道的。

答案 2 :(得分:0)

使用LINQ的另一个选项。

                    //Group strings without considering case
bool doesListPass = strings.GroupBy(s => s.ToUpper())
                    //Check that all strings in each group has the same case
                    .All(group => group.All(s => group.First() == s));

                    //Group strings without considering case
IEnumerable<string> cleanedList = strings.GroupBy(s => s.ToUpper())
                    //Check that all strings in each group has the same case
                    .Where(group => group.All(s => group.First() == s))
                    //Map all the "passing" groups to a list of strings 
                    .SelectMany(g => g.ToList());

注意:您可以根据需要使用ToUpper()或ToUpperInvariant()。

相关问题