Luaの文字列からすべてのスペースを削除したい。これは私が試したことです:
string.gsub(str, "", "")
string.gsub(str, "% ", "")
string.gsub(str, "%s*", "")
これは機能していないようです。すべてのスペースを削除するにはどうすればよいですか?
それは機能します、あなたはただ実際の結果/戻り値を割り当てる必要があります。次のバリエーションのいずれかを使用します。
str = str:gsub("%s+", "")
str = string.gsub(str, "%s+", "")
%s+
空の一致を置き換える意味がない(つまり、スペースがない)ので、私は使用します。これはまったく意味がないので、少なくとも1つのスペース文字を探します(+
数量詞を使用)。
最速の方法は、trim.cからコンパイルされたtrim.soを使用することです。
/* trim.c - based on http://lua-users.org/lists/lua-l/2009-12/msg00951.html
from Sean Conner */
#include <stddef.h>
#include <ctype.h>
#include <lua.h>
#include <lauxlib.h>
int trim(lua_State *L)
{
const char *front;
const char *end;
size_t size;
front = luaL_checklstring(L,1,&size);
end = &front[size - 1];
for ( ; size && isspace(*front) ; size-- , front++)
;
for ( ; size && isspace(*end) ; size-- , end--)
;
lua_pushlstring(L,front,(size_t)(end - front) + 1);
return 1;
}
int luaopen_trim(lua_State *L)
{
lua_register(L,"trim",trim);
return 0;
}
次のようなものをコンパイルします。
gcc -shared -fpic -O -I/usr/local/include/luajit-2.1 trim.c -o trim.so
より詳細な(他の方法との比較で):http://lua-users.org/wiki/StringTrim
使用法:
local trim15 = require("trim")--at begin of the file
local tr = trim(" a z z z z z ")--anywhere at code
次の関数を使用します。
function all_trim(s)
return s:match"^%s*(.*)":match"(.-)%s*$"
end
または短い:
function all_trim(s)
return s:match( "^%s*(.-)%s*$" )
end
利用方法:
str=" aa "
print(all_trim(str) .. "e")
出力は次のとおりです。
aae
LuaJITの場合、Lua wikiのすべてのメソッド(おそらくネイティブC / C ++を除く)は、私のテストでは非常に低速でした。この実装は最高のパフォーマンスを示しました。
function trim (str)
if str == '' then
return str
else
local startPos = 1
local endPos = #str
while (startPos < endPos and str:byte(startPos) <= 32) do
startPos = startPos + 1
end
if startPos >= endPos then
return ''
else
while (endPos > 0 and str:byte(endPos) <= 32) do
endPos = endPos - 1
end
return str:sub(startPos, endPos)
end
end
end -- .function trim
誰かが文字列の束のすべてのスペースを削除し、文字列の中央のスペースを削除しようとしている場合、これは私にとってはうまくいきます:
function noSpace(str)
local normalisedString = string.gsub(str, "%s+", "")
return normalisedString
end
test = "te st"
print(noSpace(test))
もっと簡単な方法があるかもしれませんが、私は専門家ではありません!