Lua string.reverse()
2016-08-18 本文已影响519人
AlbertS
![](https://img.haomeiwen.com/i2133677/beca2b161ed124c6.jpg)
前言#
今天的函数更加简单,字符串反转,听说过吧,把字符串第一个字符和最后一个字符交换,第二个和倒数第二个交换,以此类推,相信我们刚学习一门语言的时候都做过这个操作,在这里就不多说了,我们一起来看一下函数的用法。
string.reverse()##
- 原型:string.reverse(s)
- 解释:返回字符串
s
反序字符串
Usage##
- 首先新建一个文件将文件命名为reversetest.lua然后编写如下代码:
-- 普通字符串
local sourcestr = "I am a good person !"
print("\nsourcestr is : "..sourcestr)
-- 使用函数反转
local first_ret = string.reverse(sourcestr)
print("\nfirst_ret is : ")
print(first_ret)
-- 字符串里包括`\0`
local otherstr = "this is a string \0 hahaha "
print("\n\notherstr is : "..string.format("%q", otherstr))
-- 再次使用函数反转
first_ret = string.reverse(otherstr)
print("\nfirst_ret is : ")
print(string.format("%q", first_ret))
- 运行结果
![](https://img.haomeiwen.com/i2133677/6894c736ce70e5b8.png)
总结#
- 这个函数的作用由结果可以清楚的看出,就是把字符串反过来而已。
- 和string家族中的其它函数一样,字符
'\0'
也不会影响反转的结果。 - 呃……,看到这个函数怎么想起了宝强最近的剧情反转O(∩_∩)O~