search List for string .StartsWith()

后端 未结 10 1751
终归单人心
终归单人心 2021-01-19 00:13

I have a

List

with 1500 strings. I am now using the following code to pull out only string that start with the string prefix

10条回答
  •  时光取名叫无心
    2021-01-19 00:17

    If you have the list in alpabetical order, you can use a variation of binary search to make it a lot faster.

    As a starting point, this will return the index of one of the strings that match the prefix, so then you can look forward and backward in the list to find the rest:

    public static int BinarySearchStartsWith(List words, string prefix, int min, int max) {
      while (max >= min) {
        int mid = (min + max) / 2;
        int comp = String.Compare(words[mid].Substring(0, prefix.Length), prefix);
        if (comp < 0) {
          min = mid + 1;
        } else if (comp > 0) {
          max = mid - 1;
        } else {
          return mid;
        }
      }
      return -1;
    }
    
    int index = BinarySearchStartsWith(theList, "pre", 0, theList.Count - 1);
    if (index == -1) {
      // not found
    } else{
      // found
    }
    

    Note: If you use a prefix that is longer than any of the strings that are compared, it will break, so you might need to figure out how you want to handle that.

提交回复
热议问题