How to remove spaces from a string in Lua?

后端 未结 5 1171
臣服心动
臣服心动 2021-02-07 00:25

I want to remove all spaces from a string in Lua. This is what I have tried:

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


        
5条回答
  •  伪装坚强ぢ
    2021-02-07 00:45

    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 
    #include 
    #include 
    #include 
    
    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
    

提交回复
热议问题