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*", "")
This does not seem to work. How can I remove all of the spaces?
To remove all white spaces from String, use the replaceAll() method of String class with two arguments, i.e. Program: Java.
There are many ways to implement the "trim" function [1] in Lua: -- trim implementations function trim1(s) return (s:gsub("^%s*(. -)%s*$", "%1")) end -- from PiL2 20.4 function trim2(s) return s:match "^%s*(.
The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".
String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With