Как удалить пробелы из строки в Lua?
Я хочу удалить все пробелы из строки в Lua. Вот что я пробовал:
string.gsub(str, "", "")
string.gsub(str, "% ", "")
string.gsub(str, "%s*", "")
это, похоже, не работает. Как я могу удалить все пробелы?
4 ответов
он работает, вам просто нужно назначить фактическое значение результата / возврата. Используйте один из следующих вариантов:
str = str:gsub("%s+", "")
str = string.gsub(str, "%s+", "")
Я использую %s+ поскольку нет смысла заменять пустое совпадение (т. е. нет места). Это просто не имеет никакого смысла, поэтому я ищу хотя бы один символ пробела (используя + Квантор).
самый быстрый способ-использовать trim.так составлено из 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
вы используете следующую функцию :
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