美文网首页程序员
Lua string.reverse()

Lua string.reverse()

作者: AlbertS | 来源:发表于2016-08-18 20:30 被阅读519次
    时光反转.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))
    
    
    • 运行结果
    string_reverse.png

    总结#

    • 这个函数的作用由结果可以清楚的看出,就是把字符串反过来而已。
    • 和string家族中的其它函数一样,字符'\0'也不会影响反转的结果。
    • 呃……,看到这个函数怎么想起了宝强最近的剧情反转O(∩_∩)O~

    相关文章

      网友评论

        本文标题:Lua string.reverse()

        本文链接:https://www.haomeiwen.com/subject/erovsttx.html