local s = "hello abc"
print(string.sub(s,1,3))
print(string.find(s,"o"))--start and end index(from 1)
local gs = string.gsub("abc","a","b")--replace a to b
print(gs)
hel
5 5
bbc
local h = "hello "
local w = "world "
print(h..w)
local str = string.format("%s %s,%d,%.2f","hello","world",123,123)
print(str)
hello world
hello world,123,123.00
print(10+1+"1")
print(tostring(1))
print("input a num:")
line = io.read()
num = tonumber(line)
if num==nil then
print("input error")
else
print(num)
end
12
1
input a num:
2
2
字符操作
print(string.byte('abc',1,2))
print(string.char(97,98))
97 98
ab
gmatch:返回一个迭代器函数,通过这个迭代器函数可以遍历到在字符串s中出现模式串p的所有地方。
s = "hello world "
for w in string.gmatch(s, "%a+") do --匹配最长连续且只含字母的字符串
print(w)
end
hello
world
gsub(s, p, r [, n]):将目标字符串s中所有的子串p替换成字符串r。可选参数n,表示限制替换次数
print(string.gsub("hello world,world","world","china"))
hello china,china 2