指定長度的strstr函式

2021-06-08 18:38:13 字數 2283 閱讀 5177

前一段工作中用到了,找了幾個方法。都實現了一下,測試了下,都差不多,glibc的實現方法相比還是快一些,stristrex也不慢,至於qi_strnstr,是自己的乙個想法實現的,不過可悲的是,他是最慢的。

char *glibc_strnstr (const char *phaystack, const char *pneedle, int len)

while (a != b);

} if (!(c = *++needle))

goto foundneedle;

++needle;

goto jin;

for (;;)

else

a = *++haystack;

do}while ((a = *++haystack) != c);

}crest:

while (*++rhaystack == (a = *++needle) && pend > rhaystack);

needle = rneedle; /* took the register-poor aproach */

}if(!a)

break;

}} }

foundneedle:

return (char *) haystack;

ret0:

return 0;

}char *qi_strnstr (const char *phaystack, const char *pneedle, int len)

else if( ilen >= 4 )

else if( ilen >= 2 )

else if( ilen >= 1 )

}if(ilen == 0)

return (char*)pcur; }

return null;

}static char* _stristrex( const char * src, long src_len, const char * substr, long substr_len )

ch = *substr;

chothercase = ch;

if ( ch >= 'a' && ch <= 'z')

else if (ch > 'a' && ch <= 'z')

p = src;

pend = p + src_len;

while ( p < pend )

} p++; }

return null; }

static char* strnstr( const char * src, long src_len, const char * substr, long substr_len )

p = src;

pend = p + src_len - substr_len;

while ( p < pend )

}p++; }

return null;

}

用測試程式測試了一下。最簡單的strnstr是最快的。

static void test_strnstr()

printf("glibc_strnstr耗時 = %d\n\n", gettickcount()-start);

cs = 100*1000000;

start = gettickcount();

printf("start = %llu,cs=%d\n", start,cs);

while(cs--)

printf("qi_strnstr耗時 = %d\n\n", gettickcount()-start);

cs = 100*1000000;

start = gettickcount();

printf("start = %llu,cs=%d\n", start,cs);

while(cs--)

printf("_stristrex耗時 = %d\n\n", gettickcount()-start);

cs = 100*1000000;

start = gettickcount();

printf("start = %llu,cs=%d\n", start,cs);

while(cs--)

printf("strnstr耗時 = %d\n\n", gettickcount()-start);

指定長度路徑數

time limit 1000 ms memory limit 65536 kib submit statistic problem description 題目給出乙個有n個節點的有向圖,求該有向圖中長度為k的路徑條數。方便起見,節點編號為1,2,n,用鄰接矩陣表示該有向圖。該有向圖的節點數不少於...

指定長度路徑數

time limit 1000 ms memory limit 65536 kib submit statistic problem description 題目給出乙個有n個節點的有向圖,求該有向圖中長度為k的路徑條數。方便起見,節點編號為1,2,n,用鄰接矩陣表示該有向圖。該有向圖的節點數不少於...

指定長度路徑數

problem description 題目給出乙個有n個節點的有向圖,求該有向圖中長度為k的路徑條數。方便起見,節點編號為1,2,n,用鄰接矩陣表示該有向圖。該有向圖的節點數不少於2並且不超過500.例如包含兩個節點的有向圖,圖中有兩條邊1 2 2 1 長度為1的路徑有兩條 1 2 和 2 1 長...