雜湊尋找的優越性:
當尋找的字串長度小於機器字長時,可以把字串當做 long 進行比較。由於移位操作相當快(一個刻度),所以執行操作花費的時間比較少。
這種尋找辦法通用性不好。( big-endian or little-endian 問題)。但不可否認,它的尋找速度確實快。
// "CSDN" 的尋找演算法
// 思路是:把 "csdn" 按整數比較。每比較一次,對目標串進行移位操作。
void dwordsearch(const char pstr, const char* str )
{
const int* ptarget = (int*)str;
const int hash= *(int*)pstr;
// 出現的次數
size_t index = 0;
size_t index2 = 0;
vector< size_t > posCollect;
//如果不是整數的倍數,儲存尾巴和最後一個 int。
int len = strlen( str ) - strlen( str ) % sizeof( int );
const char* end = str + len ;
if ( *end )
{
cout << "有尾巴" << endl;
}
// 判斷開頭相等不
//
if ( hash == ptarget[index] )
{
cout << "找到了" << endl;
}
// 判斷結尾相等不
// 以後再加吧。
for( index = 0; index < len / 4 - 1; index++ )
{
for( index2 = 8;index2 <= 32; index2 += 8 )
{
// 向左移?向右移?視 big-endding 和 small-endding 不同而不同
if ( hash == ( ( ptarget[index] >> index2 ) | ( ptarget[index+1] << ( 32- index2 ) ) ) )
{
break;
}
}
if( index2 <= 32 )
{
posCollect.push_back( index * 4 + index2 / 8 );
}
}
cout << "找到的次數:" << posCollect.size() << endl;
for( vector<size_t>::const_iterator iter = posCollect.begin(); iter!= posCollect.end(); iter++ )
{
cout << *iter << endl;
}
system( "pause" );
}