Search code examples
stringluagsublua-patterns

String Manipulation in Lua: Make the odd char uppercase


I'm trying to do a library in Lua with some function that manipulate strings. I want to do a function that changes the letter case to upper only on odd characters of the word.

This is an example:

Input: This LIBRARY should work with any string!
Result: ThIs LiBrArY ShOuLd WoRk WiTh AnY StRiNg!

I tried with the "gsub" function but i found it really difficult to use.


Solution

  • First, split the string into an array of words:

    local original = "This LIBRARY should work with any string!"
    
    local words = {}
    for v in original:gmatch("%w+") do 
        words[#words + 1] = v
    end
    

    Then, make a function to turn words like expected, odd characters to upper, even characters to lower:

    function changeCase(str)
        local u = ""
        for i = 1, #str do
            if i % 2 == 1 then
                u = u .. string.upper(str:sub(i, i))
            else
                u = u .. string.lower(str:sub(i, i))
            end
        end
        return u
    end
    

    Using the function to modify every words:

    for i,v in ipairs(words) do
        words[i] = changeCase(v)
    end
    

    Finally, using table.concat to concatenate to one string:

    local result = table.concat(words, " ")
    print(result)
    -- Output: ThIs LiBrArY ShOuLd WoRk WiTh AnY StRiNg