Lua程序设计第4版第4章课后答案

4.1

s = [==[<![CDATA[
    Hello world
  ]]>]==]

print(s)

4.2
4.2节,多行16进制+\z

4.3

function f43(s,n,t)
    s1 = ""
    s2 = ""
    if n>1 then
        s1= string.sub(s,1,n-1)
    end
    s2 = string.sub(s,n)
    return s1..t..s2
end
print(f43("hello world",1,"start: "))
print(f43("hello world",7,"small: "))

4.4 sub拼接,那些字符我都打不出来

4.5 略,利用sub字符串拼接

4.6
使用sub

4.7
直接使用reverse函数
或者像我一样使用byte一个一个字符进行比较

function f47(s)
    i = 1
    j=string.len(s)
    while i<j do
        if s:byte(i)~=s:byte(j) then
            return false
        end
        i = i+1
        j= j-1
    end
    return true
end
print(f47("step on no pets"))
print(f47("banana"))

4.8

function f47(s)
    s = string.gsub(s,"%p","")
    s = string.gsub(s," ","")
    i = 1
    j=string.len(s)
    while i<j do
        if s:byte(i)~=s:byte(j) then
            return false
        end
        i = i+1
        j= j-1
    end
    return true
end
print(f47("step on no  ,,,,pets"))
print(f47("banana"))

4.9
byte无法用于比较,就用codepoint加offset来比较每一个字符。

function f47(s)
    s = string.gsub(s,"%p","")
    s = string.gsub(s," ","")
    i = 1
    j=utf8.len(s)
    while i<j do
        if utf8.codepoint(s,utf8.offset(s,i))~=utf8.codepoint(s,utf8.offset(s,j)) then
            return false
        end
        i = i+1
        j= j-1
    end
    return true
end
print(f47("step on no  ,,,,pets"))
print(f47("banana"))
发布了77 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Icecoldless/article/details/104076195
今日推荐