将字符串每隔n个字符拆分一次。

huangapple go评论50阅读模式
英文:

How would i split a string once every n characters

问题

让我们假设我有一个字符串:

local n = 2
local Name = "JohnIsNice"

如何将它每隔n个字符拆分,使字符串变成
{"Jo", "hn", "Is", "Ni", "Ce"}

我不太清楚如何做,所以任何帮助将不胜感激。

英文:

Let's say i have a string:

local n = 2
local Name = "JohnIsNice"

How would i split it every n characters so the string will become
{"Jo", "hn", "Is", "Ni", "Ce"}

I don't really know how to do it so any help would be appreciated

答案1

得分: 2

('.'):rep(n) 会生成一个包含 n 个点的字符串,表示匹配 n 个字符的模式。

Name:gmatch() 返回所有匹配项。

英文:
for m in Name:gmatch(('.'):rep(n)) do
  print(m)
end

('.'):rep(n) will generate a string with n dots which represents a pattern matches n characters.

Name:gmatch() returns all the matches.

huangapple
  • 本文由 发表于 2023年5月7日 21:45:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76194310.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定