復制拼接.jpg
前言#
今天的函數(shù)也比較簡單,就是字符串的復制拼接驯鳖,如果不使用這個函數(shù)而使用..
操作符也是可以的肆氓,但是還得用到循環(huán)和反復申請空間袍祖,既費時又費力,有了這個函數(shù)就方便多了谢揪,我們一起來看一下蕉陋。
string.rep()##
- 原型:string.rep(s, n)
- 解釋:返回字符串
s
串聯(lián)n
次的所組成的字符串,參數(shù)s
表示基礎字符串拨扶,參數(shù)n
表示賦值的次數(shù)凳鬓。
Usage##
- 首先新建一個文件將文件命名為reptest.lua然后編寫如下代碼:
-- 普通字符串
local sourcestr = "this is a string "
print("\nsourcestr is : "..sourcestr)
-- 使用函數(shù)拼接
local first_ret = string.rep(sourcestr, 3)
print("\nfirst_ret is : "..first_ret)
-- 使用操作符`..`拼接
local second_ret = sourcestr
for i=1, 2 do
second_ret = second_ret..sourcestr
end
print("\nsecond_ret is : "..second_ret)
-- 字符串里包括`\0`
local otherstr = "this is a string \0 hahaha "
print("\notherstr is : "..string.format("%q", otherstr))
-- 再次使用函數(shù)拼接
first_ret = string.rep(otherstr, 3)
print("\nfirst_ret is : "..string.format("%q", first_ret))
-- 再次使用操作符`..`拼接
second_ret = otherstr
for i=1, 2 do
second_ret = second_ret..otherstr
end
print("\nsecond_ret is : "..string.format("%q", second_ret))
- 運行結果
string_rep.png
總結#
- 由前三組結果可以看出使用函數(shù)
string.rep()
和使用操作符..
效果是一樣的,但是推薦使用函數(shù)string.rep()
患民,因為查過相關的資料說大量迭代使用操作符..
費時費力缩举。 - 由前三組結果和后三組結果對比可以看出
string.rep()
在遇到\0
時不會認為是字符串結尾,而是把字符串的所有內容都拼接起來匹颤。