
復(fù)制拼接.jpg
前言#
今天的函數(shù)也比較簡單,就是字符串的復(fù)制拼接,如果不使用這個函數(shù)而使用..操作符也是可以的,但是還得用到循環(huán)和反復(fù)申請空間,既費(fèi)時又費(fèi)力,有了這個函數(shù)就方便多了,我們一起來看一下。
string.rep()##
- 原型:string.rep(s, n)
- 解釋:返回字符串
s串聯(lián)n次的所組成的字符串,參數(shù)s表示基礎(chǔ)字符串,參數(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))
- 運(yùn)行結(jié)果

string_rep.png
總結(jié)#
- 由前三組結(jié)果可以看出使用函數(shù)
string.rep()和使用操作符..效果是一樣的,但是推薦使用函數(shù)string.rep(),因為查過相關(guān)的資料說大量迭代使用操作符..費(fèi)時費(fèi)力。 - 由前三組結(jié)果和后三組結(jié)果對比可以看出
string.rep()在遇到\0時不會認(rèn)為是字符串結(jié)尾,而是把字符串的所有內(nèi)容都拼接起來。