How to remove spaces from a string in Lua?

For LuaJIT all methods from Lua wiki (except for, possibly, native C/C++) were awfully slow in my tests. This implementation showed the best performance:

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

It works, you just have to assign the actual result/return value. Use one of the following variations:

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

I use %s+ as there's no point in replacing an empty match (i.e. there's no space). This just doesn't make any sense, so I look for at least one space character (using the + quantifier).


You use the following function :

function all_trim(s)
  return s:match"^%s*(.*)":match"(.-)%s*$"
end

Or shorter :

function all_trim(s)
   return s:match( "^%s*(.-)%s*$" )
end

usage:

str=" aa " 
print(all_trim(str) .. "e")

Output is:

aae

The fastest way is to use trim.so compiled from 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;
}

compile something like:

gcc -shared -fpic -O -I/usr/local/include/luajit-2.1 trim.c -o trim.so

More detailed (with comparison to the other methods): http://lua-users.org/wiki/StringTrim

Usage:

local trim15 = require("trim")--at begin of the file
local tr = trim("   a z z z z z    ")--anywhere at code

Tags:

Replace

Lua