How to remove spaces from a string in Lua?

后端 未结 5 1204
臣服心动
臣服心动 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:54

    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
    

提交回复
热议问题