是否有任何标准函数来搜索字符串中相同的子字符串?

时间:2014-05-29 10:35:58

标签: c# string function substring

如果我对一个示例string"ABEFAB",则需要一个长度参数(eg. 2),然后返回一个结果,该结果将显示ARE identical substringsstring中的那个长度。

3 个答案:

答案 0 :(得分:1)

我认为你正在寻找这个

public static bool HasIdenticalSubStrings(string str, int len)
{
    bool returnValue = false;

    List<String> lst = new List<string>();

    for (int i = 0; i <= str.Length - len; i++)
        lst.Add(str.Substring(i, len));

    returnValue = (lst.Distinct().Count() != lst.Count);

    return returnValue;
}

并调用

HasIdenticalSubStrings("ABEFAB", 2); //return true

HasIdenticalSubStrings("ABCDEF", 2); //return false

注意:您需要执行一些检查,例如String.IsNullOrEmpty检查

高效方法:

public static bool HasIdenticalSubStrings(string str, int len)
{
    bool returnValue = false;

    List<String> lst = new List<string>();

    for (int i = 0; i <= str.Length - len; i++)
    {
        String tempstr = str.Substring(i, len);
        if (lst.Contains(tempstr))
        {
            returnValue = true;
            break;
        }
        else
            lst.Add(tempstr);
    }

    return returnValue;
}

答案 1 :(得分:1)

最简单的(但不是高效的)解决方案

public static Boolean HasIdenticalSubStrings(String value, int length) 
{
  if (length <= 0)
    return false;
  else if (String.IsNullOrEmpty(value))
    return false;
  else if (value.Length <= length)
    return false;

  // HashSet is more efficient than List for Contains() operation
  HashSet<String> subStrings = new HashSet<String>();

  for (int i = 0; i <= value.Length - length; ++i) {
    String s = value.Substring(i, length);

    if (subStrings.Contains(s))
      return true;
    else
      subStrings.Add(s);
  }

  return false;
}

测试用例:

  HasIdenticalSubStrings("AAA", 2);    // true, overlaping "AA" substrings
  HasIdenticalSubStrings("ABxyAB", 2); // true
  HasIdenticalSubStrings("ABxAB", 2);  // true
  HasIdenticalSubStrings("ABCDEF", 2); // false

答案 2 :(得分:0)

我认为Contains很好地适应了这种瞳孔。但是它不需要任何长度参数,但是我发现对于我的程序它甚至不需要,因为我使用了确定的块大小。