使用lua去除string中得空格
时间: 2023-10-07 12:06:02 浏览: 41
在Lua中,可以使用字符串函数 `string.gsub()` 或者 `string.gmatch()` 来去除字符串中的空格。以下是两个示例代码:
1. 使用 `string.gsub()` 去除字符串中的空格
```
local str = " Hello, world! "
local str_without_spaces = string.gsub(str, "%s+", "")
print(str_without_spaces) -- 输出 "Hello,world!"
```
解释一下代码的执行过程:
1. 将字符串" Hello, world! "赋值给变量str。
2. 使用string库中的gsub函数,将str中的所有空格替换为空字符串,得到去除空格后的字符串。
3. 将去除空格后的字符串打印出来,得到输出结果为"Hello,world!"。
2. 使用 `string.gmatch()` 去除字符串中的空格
```
local str = " Hello, world! "
local str_without_spaces = ""
for word in string.gmatch(str, "%S+") do
str_without_spaces = str_without_spaces .. word
end
print(str_without_spaces) -- 输出 "Hello,world!"
```
解释一下代码的执行过程:
1. 将字符串" Hello, world! "赋值给变量str。
2. 使用string库中的gmatch函数,将str中的所有非空格字符提取出来,然后拼接为一个新的字符串。
3. 将去除空格后的字符串打印出来,得到输出结果为"Hello,world!"。
无论使用 `string.gsub()` 还是 `string.gmatch()`,都可以去除字符串中的空格。