2025年11月5日 星期三

Lua for V A P O R C O D E

 7 kyu: V A P O R C O D E

題目是將一串文字,轉成VAPOR code的形式。
我的寫法如下:
local function vaporcode(s)
  local a = ""
  for i = 1, #s do
    local u = s:sub(i, i):upper()
    if u ~= " " then
      a = a .. u .. "  "
    end
  end
    return a:sub(1, -3)
end

return vaporcode
但是別人簡潔的寫法如下:
local function vaporcode(s)
  return s:upper():gsub("%s",""):gsub("%S","%1  "):sub(1,-3)
end

return vaporcode
In Lua's string.gsub function, %1 (or %n where n is a number from 1 to 9) is used in the replacement string to refer to a captured substring from the pattern.
Note: %1是從左到右在pattern中的第1個%值。
例如:
local text = "Hello World"local new_text, count = string.gsub(text, "(%a+)(%s+)(%a+)", "%3%2%1")print(new_text) -- Output: World Helloprint(count) -- Output: 1

%1是抓到Hello
%2是抓到空白" "
%3是抓到World

沒有留言:

張貼留言

Lua for V A P O R C O D E

 7 kyu: V A P O R C O D E 題目是將一串文字,轉成VAPOR code的形式。 我的寫法如下: local function vaporcode ( s ) local a = "" for i = 1 , # s...