使用分号分隔的字符串,转换成 ASCII 写入一个新字符串中

类似于这样的字符串即将出现:

str="Hello;this;is;a;text"

我想得到的结果是:

result="72:101:108:108:111;116:104:105:115;..."

这应该是 ASCII 中的文本。

点赞
用户6792759
用户6792759

在 Lua 中查找特定字符或字符串(例如“;”)可以使用 string.find 函数 - https://www.lua.org/pil/20.1.html

将字符转换为其 ASCII 码可以使用 string.byte 函数 - https://www.lua.org/pil/20.html

你需要做的是使用上述两个函数构建一个新字符串。如果你需要更多基于字符串的函数,请访问官方 Lua 网站:https://www.lua.org/pil/contents.html

2016-09-15 08:37:37
用户1009479
用户1009479

你可以使用字符串匹配来获取由;分隔的每个单词,然后转换、拼接:

local str = "Hello;this;is;a;text"
for word in str:gmatch("[^;]+") do
  ascii = table.pack(word:byte(1, -1))
  local converted = table.concat(ascii, ":")
  print(converted)
end

上面代码的输出是:

72:101:108:108:111
116:104:105:115
105:115
97
116:101:120:116

剩下的工作就留给你了。提示:使用table.concat

2016-09-15 08:39:21
用户107090
用户107090

下面是另一种方法,利用了gsub接受读取替换的表的事实:

T={}
for c=0,255 do
    T[string.char(c)]=c..":"
end
T[";"]=";"

str="Hello;this;is;a;text"
result=str:gsub(".",T):gsub(":;",";")
print(result)
2016-09-15 12:52:24
用户6834137
用户6834137

好的...我已经深入进去了,但我找不到如何返回一个由两个不同字符串组成的字符串,如下所示:

str = str1 &" "& str2
2016-09-15 13:50:05
用户3735873
用户3735873

另一个可能性:

function convert(s)
  return (s:gsub('.',function (s)
                       if s == ';' then return s end
                       return s:byte()..':'
                     end)
           :gsub(':;',';')
           :gsub(':$',''))
end

print(convert 'Hello;this;is;a;text')

将字符串 s 中的每个字符转换为它对应的 ASCII 码,且在每个数值后面加上冒号 :,但保留分号 ;。最后删除末尾的冒号。 输出结果为:72:101:108:108:111;116:104:105:115;105:115;97;116:101:120:116

2016-09-16 14:29:53