28

Luaの文字列からすべてのスペースを削除したい。これは私が試したことです:

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

これは機能していないようです。すべてのスペースを削除するにはどうすればよいですか?

4

5 に答える 5

46

それは機能します、あなたはただ実際の結果/戻り値を割り当てる必要があります。次のバリエーションのいずれかを使用します。

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

%s+空の一致を置き換える意味がない(つまり、スペースがない)ので、私は使用します。これはまったく意味がないので、少なくとも1つのスペース文字を探します(+数量詞を使用)。

于 2012-05-05T10:02:58.193 に答える
3

最速の方法は、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
于 2014-11-29T12:34:22.783 に答える
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
于 2014-12-13T03:17:18.863 に答える
2

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
于 2018-01-18T18:42:37.870 に答える
-1

誰かが文字列の束のすべてのスペースを削除し、文字列の中央のスペースを削除しようとしている場合、これは私にとってはうまくいきます:

function noSpace(str)

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

  return normalisedString

end

test = "te st"

print(noSpace(test))

もっと簡単な方法があるかもしれませんが、私は専門家ではありません!

于 2019-05-23T12:44:41.087 に答える