字串取代 |
|
執行字串搜尋及取代時,很多時候我們不需要 string.gsub 函數附帶的正規表示式功能。針對這個新函數,我執行了一個基準測試,發現它整體上比 gsub
快了超過兩倍。在對數千個記錄的欄位值執行搜尋及取代時,可以輕易看出速度差異。
我選擇命名這個函數為「replace」是因為 Python、Ruby 和大多數程式語言在字串搜尋及取代函數中都使用「replace」。
--Sam Lie
static int str_replace(lua_State *L) { size_t l1, l2, l3; const char *src = luaL_checklstring(L, 1, &l1); const char *p = luaL_checklstring(L, 2, &l2); const char *p2 = luaL_checklstring(L, 3, &l3); const char *s2; int n = 0; int init = 0; luaL_Buffer b; luaL_buffinit(L, &b); while (1) { s2 = lmemfind(src+init, l1-init, p, l2); if (s2) { luaL_addlstring(&b, src+init, s2-(src+init)); luaL_addlstring(&b, p2, l3); init = init + (s2-(src+init)) + l2; n++; } else { luaL_addlstring(&b, src+init, l1-init); break; } } luaL_pushresult(&b); lua_pushnumber(L, (lua_Number)n); /* number of substitutions */ return 2; } /* note: add new the 'replace' function to strlib */ static const luaL_reg strlib[] = { {"len", str_len}, {"sub", str_sub}, {"lower", str_lower}, {"upper", str_upper}, {"char", str_char}, {"getchar", str_getchar}, {"rep", str_rep}, {"byte", str_byte}, {"format", str_format}, {"dump", str_dump}, {"find", str_find}, {"gfind", gfind}, {"gsub", str_gsub}, {"replace", str_replace}, {NULL, NULL} };