string API

string库

byte方法,返回byte值:

[plain]  view plain  copy
  1. print(string.byte("abc")) --97  
  2. print(string.byte("abc", 2, 3)) --98 99  


char方法,连接char成字符串:

[plain]  view plain  copy
  1. print(string.char(100,101,102)) --def  

find方法,查找子字符串的起始和结束下标:

[plain]  view plain  copy
  1. local s = "It's 10 o'clock in the morning."  
  2. local p = "%d+ o'"  
  3. print(string.find(s,p)) --6 10  
  4. print(string.find(s,p,7)) --7 10  
  5. print(string.find(s,p,1,true)) --nil  
  6. print(string.find(s,"o'",1,true)) --9 10  

第三个参数代表从第几个字符开始查找,第四个参数表示是否是明文(即不使用变量模式)

match方法,查找子字符串:

[plain]  view plain  copy
  1. local s = "Today is 10/10/2016"  
  2. local p = "%d+/%d+/%d+"  
  3. print(string.match(s,p)) --10/10/2016  
  4. print(string.match(s,p,11)) --0/10/2016  

format方法,格式化字符串:

[plain]  view plain  copy
  1. print(string.format("%d,%f,%x,%s",10,7.25,92,"num")) -- 10,7.250000,5c,num  

gmach方法,返回匹配模式的遍历:

[plain]  view plain  copy
  1. local s = "Hello world from lua"  
  2. for w in string.gmatch(s,"%a+") do  
  3.     print(w)  
  4. end  

len方法,返回长度:

[plain]  view plain  copy
  1. print("") --0  
  2. print("a\000bc\000") --5  
lower方法,转换成小写字母:

[plain]  view plain  copy
  1. print(string.lower("LUA")) --lua  
upper方法,转换成大写字母:

[plain]  view plain  copy
  1. print(string.upper("lua")) --LUA  


rep方法,重复字符串:

[plain]  view plain  copy
  1. print(string.rep("hia",3)) --hiahiahia  
reverse方法,翻转字符串:

[plain]  view plain  copy
  1. print(string.reverse("lemon")) --monel  

sub方法,子串:

[plain]  view plain  copy
  1. print(string.sub("function"),5,8) --tion  

gsub方法,替换子串,返回替换后的字符串和被替换的次数:

[plain]  view plain  copy
  1. local s = "All over the world"  
  2. lcoal p = "l"  
  3. local r = "x"  
  4. print(string.gsub(s,p,r))  --Axx over the worxd 3  
  5. print(string.gsub(s,p,r,1)) --Axl over the world 1  
  6. print(string.gsub(s,p,r,2)) --Axx over the world 2  
  7. print(string.gsub(s,p,r,3)) --Axx over the worxd 3  
  8. print(string.gsub(s,p,r,4)) --Axx over the worxd 3  

dump方法,将传入的function转换成二进制的形式,这样就可以使用loadstring来获取function的副本。function必须是不包含upvalues的Lua function。
[plain]  view plain  copy
  1. local function DumpTest()  
  2.     print("Test")  
  3. end  
  4. local a = string.dump(DumpTest)  
  5. print(a)  
  6. local b = loadstring(a)  
  7. print(b)  
  8. b()  

猜你喜欢

转载自blog.csdn.net/qq_14914623/article/details/80716757
今日推荐