Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove spaces from a string in Lua?

Tags:

replace

lua

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?

like image 254
Village Avatar asked May 05 '12 08:05

Village


People also ask

How do I remove all spaces from a string?

To remove all white spaces from String, use the replaceAll() method of String class with two arguments, i.e. Program: Java.

How do I trim a string in Lua?

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*(.

How do I reduce the space of a string?

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 "".

How do you remove spaces before and after a string?

String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.


2 Answers

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).

like image 92
Mario Avatar answered Oct 06 '22 13:10

Mario


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 
like image 24
Vyacheslav Avatar answered Oct 06 '22 14:10

Vyacheslav