在C#中优化字符串操作
2010-09-30 22:34:50 来源:WEB开发网3、从零开始写的文本搜索的方法
现在,到了的最有趣的部分。IndexOf方法搜索一个字符时是相当快的,但搜索一个单词是缓慢的,如何有一个更快的方式在字符串内搜索单词呢?
花了一些时间,为寻找可能最快的的解决办法,以下方法是我想出的。
static int FastIndexOf(string source, string pattern) {
bool found;
int limit = source.Length - pattern.Length + 1;
if (limit < 1) return -1;
// Store the first 2 characters of "pattern"
char c0 = pattern[0];
char c1 = pattern.Length > 1 ? pattern[1] : ' ';
// Find the first occurrence of the first character
int first = source.IndexOf(c0, 0, limit);
while (first != -1) {
// Check if the following character is the same like the 2nd character of "pattern"
if (pattern.Length > 1 && source[first + 1] != c1) {
first = source.IndexOf(c0, ++first, limit - first);
continue;
}
// Check the rest of "pattern" (starting with the 3rd character)
found = true;
for (int j = 2; j < pattern.Length; j++)
if (source[first + j] != pattern[j]) {
found = false;
break;
}
// If the whole word was found, return its index, otherwise try again
if (found) return first;
first = source.IndexOf(c0, ++first, limit - first);
}
return -1;
}
更多精彩
赞助商链接