Still the same string

it is printing Ab to putput instead of aB:

local function SwitchCases(String: string)

		local NewTable  = string.split(String,"")
		
		for i,v in pairs(NewTable) do
			if v == v:lower() then
				String = string.gsub(String, String.char(i), v:upper())
			else
				String = string.gsub(String, String.char(i), v:lower())
				 
			end
		end
		return String
	end
	



local D = SwitchCases("Ab")


print(D)













You’re splitting by nothing so the only result of the split table is the string itself. The string “Ab” does not match any of your if cases so none of the modifications are made. What you can do is pass a replacement function to gsub instead and invert the matched case.

-- Apply a function to abstract so we don't have to write the same
-- global substitution every time.
local function switchCases(str: string): string
    -- Check for matches of %a (any upper or lower case letter) and apply
    -- a global substitution to each match via function. Return the full
    -- result of the substitution when complete.
	return string.gsub(str, "%a", function(case)
        -- If the matched case equals the lowercase version, it's a lowercase
        -- letter. Complete the substitution by returning it in upper.
		if case == string.lower(case) then
			return string.upper(case)
        -- Same as the above case but in reverse.
		elseif case == string.upper(case) then
			return string.lower(case)
		end
	end)
end

print(switchCases("Ab")) --> aB
print(switchCases("aB")) --> Ab
2 Likes

actually no, i am splitting them by charcaters.

try in output.

example:

print(string.split("ks",""))

i will print:

[1] = “s”,
[2] = “k”

local function switchCases(inputString)
	local outputString = ""
	local charTable = inputString:split("")
	for _, char in ipairs(charTable) do
		if char == char:lower() then
			outputString..=char:upper()
		elseif char == char:upper() then
			outputString..=char:lower()
		end
	end
	return outputString
end

print(switchCases("Hello world!")) --hELLO WORLD!
local function switchCases(iS)
	local oS = ""
	for char in iS:gmatch(".") do
		if char == char:upper() then
			oS..=char:lower()
		elseif char == char:lower() then
			oS..=char:upper()
		end
	end
	return oS
end

print(switchCases("Hello world!")) --hELLO WORLD!