性能较优的 在大字符数组中找到小字符数组 C#

性能较优的 在大字符数组中找到小字符数组 C#

public static bool ContainsChars(this char[] source, char[] target,out int index)
{
     int targetLength = target.Length - 1;
     int count = 0;
     char currentCharToSearch = target[0];
     for(int i=0; i<source.Length; i++)
     {
          if (source[i] == currentCharToSearch)
          {
              count++;
              if (count == targetLength) 
              {
                  index = i - count + 1;
                  return true;
              }
              else
              {
                  currentCharToSearch = target[count];
              }
           }
           else
           {
               count = 0;
               currentCharToSearch = target[0];
           }
      }
      index = -1;
      return false;
}

使用

var c1 = new char[] { 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'h', 't' };
var c2 = new char[] { 'c', 'h', 't' };

int index;
var result = c1.ContainsChars(c2,out index); // true index = 6

c2 = new char[] { 'c', 't', 'h' };
var result2 = c1.ContainsChars(c2,out index); // false index = -1

来源:https://stackoverflow.com/questions/21636941/find-small-char-array-in-large-char-array-c-sharp

原文地址:https://www.cnblogs.com/guqiangjs/p/7283418.html