如何从在Lua字符串中的空格?(How to remove spaces from a string

2019-07-29 06:36发布

我想从Lua中的字符串中删除所有的空格。 这是我曾尝试:

string.gsub(str, "", "")
string.gsub(str, "% ", "")
string.gsub(str, "%s*", "")

这似乎并没有工作。 如何删除所有的空间?

Answer 1:

它的工作原理,你就必须分配实际结果/返回值。 使用下列变化之一:

str = str:gsub("%s+", "")
str = string.gsub(str, "%s+", "")

我用%s+ ,因为在更换空的匹配(即没有空间)是没有意义的。 这只是没有任何意义,所以我找了至少一个空格字符(使用+量词)。



Answer 2:

最快的方法是使用trim.so从trim.c编译:

/* 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


Answer 3:

您可以使用以下功能:

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


Answer 4:

对于LuaJIT从Lua维基的所有方法(除了可能的话,本地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


Answer 5:

如果有人希望删除一串字符串的所有空间,并删除字符串中间的空间,这个这个工作对我来说:

function noSpace(str)

  local normalisedString = string.gsub(str, "%s+", "")

  return normalisedString

end

test = "te st"

print(noSpace(test))

可能是有,虽然更简单的方法,我不是专家!



文章来源: How to remove spaces from a string in Lua?
标签: lua replace