如何在Lua中从字符串中删除空格?

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

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

这似乎无法正常工作。如何删除所有空格?

原文链接 https://stackoverflow.com/questions/10460126

点赞
stackoverflow用户409744
stackoverflow用户409744

它运行良好,你只需要赋值实际的结果/返回值。使用下列其中一种变体:

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

我使用 %s+ 是因为没有替换空匹配的意义(即没有空格)。这是没有意义的,所以我寻找至少一个空格字符(使用 + 量化器)。

2012-05-05 10:02:58
stackoverflow用户1979882
stackoverflow用户1979882

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

/* trim.c - 基于 http://lua-users.org/lists/lua-l/2009-12/msg00951.html 
            作者为 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")--在文件开头引入
local tr = trim("   a z z z z z    ")--在代码中任何位置使用
2014-11-29 12:34:22
stackoverflow用户1058591
stackoverflow用户1058591

你可以使用以下函数:

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
2014-12-13 03:17:18
stackoverflow用户7875310
stackoverflow用户7875310

对于 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
2018-01-18 18:42:37
stackoverflow用户11544408
stackoverflow用户11544408

如果有人想去除一堆字符串中的所有空格,并且去除字符串中间的空格,这对我来说很有效:

function noSpace(str)

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

  return normalisedString

end

test = "te st"

print(noSpace(test))

也许有更简单的方法,但我不是专家!

2019-05-23 12:44:41