如果要写一个从字符串中查找一个字符的函数,相信你不难想到如下代码:
1 char* __cdecl strchr_1( 2 char const* _Str, 3 int _Val 4 ) { 5 6 while (*_Str && *_Str != _Val) 7 _Str++; 8 9 if (*_Str == _Val) 10 return(_Str); 11 12 return NULL; 13 }
和 strlen 的效率之旅一样,我们先做好测试脚手架:
1 typedef char* (__cdecl* p_strchr)( 2 char const* _Str, 3 int _Val 4 ); 5 6 // 测试正确性 7 void test_function( 8 char* funName, 9 p_strchr function, 10 char* str, 11 char ch, 12 int expectIndex) { 13 int got = function(str, ch) - (int)str; 14 printf( 15 "func [%s] test value [%s] find char [%c]," 16 " expect [%d], got [%d], %s ", 17 funName, 18 str, 19 ch, 20 got, 21 expectIndex, 22 got == expectIndex 23 ? "true" 24 : "false" 25 ); 26 } 27 28 // 正确性测试用例 29 void test_functions(char* funName, p_strchr function) { 30 struct test_item { 31 32 char* str; 33 char val; 34 int expect_index; 35 } items[] = { 36 // return NULL, expect nagtive address of "a" 37 { "a", 'b', -(int)"a" }, 38 // last is ' ', returns 1 39 { "a", '