检测字符串是否适合字符串序列的最快方法

时间:2021-05-10 14:53:59

标签: c# sequence

想象一个像这样的字符串序列:

  • aa11
  • aa12
  • aa13
  • .....
  • aa99
  • ab11
  • ....
  • az99
  • ba11
  • ....
  • zz99

我想检测由 teststartString 确定的字符串序列之间是否存在 endString 字符串。例如:

string test = "cc53";
string test2 = "hf15"

string startString = "aa11";
string endString = "ff99";

test.ExistsInBetween(startString, endString)   // must be true
test2.ExistsInBetween(startString, endString)  // must be false

public static bool ExistsInBetween(this string input, string start, string end)
{
    // I don't know where to begin
}

我已经尝试(成功)将开始和结束之间的所有字符串生成为 HashSet<string> 并运行 hash.Contains(test),但是您可以想象这对于较长的字符串表现非常差。

注意事项:

  1. 字符串可以有不同的长度(但是,在给定的测试中,三个字符串的长度总是相同的)
  2. 字符只能是数字或数字和字母

1 个答案:

答案 0 :(得分:2)

一个简单的 string.Compare 应该可以工作:

public static class StringExtensions
{
    public static bool ExistsInBetween(this string input, string start, string end)
    {
        return string.Compare(input, start) >= 0 && string.Compare(input, end) <= 0;
    }
}
相关问题