检测字符串是否适合字符串序列的最快方法
Fastest way to detect if a string fits in a sequence of strings
想象一下这样的字符串序列:
- aa11
- aa12
- aa13
- .....
- aa99
- ab11
- .....
- az99
- ba11
- .....
- zz99
我想检测 test
字符串是否存在于由 startString
和 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)
,但是正如您可以想象的那样,它的表现非常糟糕更长的字符串。
注意事项:
- 字符串的长度可以不同(但是,在给定的测试中,三个字符串的长度始终相同)
- 字符只能是数字或数字加字母
一个简单的 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;
}
}
想象一下这样的字符串序列:
- aa11
- aa12
- aa13
- .....
- aa99
- ab11
- .....
- az99
- ba11
- .....
- zz99
我想检测 test
字符串是否存在于由 startString
和 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)
,但是正如您可以想象的那样,它的表现非常糟糕更长的字符串。
注意事项:
- 字符串的长度可以不同(但是,在给定的测试中,三个字符串的长度始终相同)
- 字符只能是数字或数字加字母
一个简单的 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;
}
}