【发布时间】:2012-05-14 15:57:30
【问题描述】:
我想从 Lua 中的字符串中删除所有空格。这是我尝试过的:
string.gsub(str, "", "")
string.gsub(str, "% ", "")
string.gsub(str, "%s*", "")
这似乎不起作用。如何删除所有空格?
【问题讨论】:
我想从 Lua 中的字符串中删除所有空格。这是我尝试过的:
string.gsub(str, "", "")
string.gsub(str, "% ", "")
string.gsub(str, "%s*", "")
这似乎不起作用。如何删除所有空格?
【问题讨论】:
它有效,您只需分配实际的结果/返回值。使用以下变体之一:
str = str:gsub("%s+", "")
str = string.gsub(str, "%s+", "")
我使用%s+,因为没有必要替换空匹配项(即没有空格)。这没有任何意义,所以我寻找至少一个空格字符(使用+ 量词)。
【讨论】:
+,您将一次性替换彼此之后的空格,这可能会更高效(不确定它在 Lua 中是否真的很重要)。
最快的方法是使用从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
【讨论】:
s:match( "^%s*(.-)%s*$" ).
stdin:1: attempt to concatenate a nil value
nil 作为任何输入字符串的结果。你返回结果了吗?还是您忘记了"e" 周围的引号?
function all_trim(s) return s:match( "^%s*(.-)%s*$" ) end; str = " aa "; print( all_trim( str ) .. "e" )。这在这里工作得很好。
return。
对于 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))
不过可能有更简单的方法,我不是专家!
【讨论】: