-- 3.宣告一個function,輸入一段字串,將該字串用空白字符分割,結果裝到陣列回傳,若輸入非字串要報錯
-- ex:
-- input : "This is a sentence"
-- return : {[1] : "This", [2] : "is", [3] : "a", [4] : "sentence"}
-- input : 100
-- return : "Error, input must be a string"

function EX_3(x)
    if(type(x) == "string") then
        local array={}
        local s = "{"
        i = 1
        for word in string.gmatch(x, "%S+") do
            array[i] = word
            s = s .. "["..i.."] :" .." \"".. array[i] .."\", "
            i = i + 1
        end
        s = s .."}"
        s = string.gsub(s,", }", "}")
        print(s)
        
    else
        print("Error, input must be a string")
    end
end

input = "This is a sentence"
EX_3(input)

-- print("-----------------")

-- function EX_3(x)
--     if(type(x) == "string") then
--         local array={}
--         i = 1
--         for word in string.gmatch(x, "%S+") do
--             array[i] = word
--             i = i + 1
--         end
--         -- print(table.concat(array,", "))
--         for key, val in pairs(array) do
--             print("["..key.."] " .. ": "..val)
--         end
        
--     else
--         print("Error, input must be a string")
--     end
-- end

-- input = "This is a sentence"
-- EX_3(input)



Embed on website

To embed this program on your website, copy the following code and paste it into your website's HTML: