Coding Challenge #8: snake_case to camelCase

Coding Challenge #8

Hello! It’s been a long time since we met isn’t it. Sorry for being lazy. I hope I manage to revive this series, and actual continue it. I am still looking for people to help me out and make challenges as well! So if you’re interested, help me out!

As usual, same requirements:

  • Has to be written in Lua 5.1 (the version roblox uses)
  • The program has to be compatible with Roblox Studio, meaning you can’t use features vanilla Lua has but rbxlua disabled
  • You can’t use httpservice to cheat the challenge

Your company has a new CEO, and this new CEO hates the snake_case naming convention so much! He wants you to convert all snake_case variables names to camelCase.

Write a function camelCase(s), where s is a string containing a snake_case name, that returns the camelCase version of snake_case.

camelCase("snake_case") --snakeCase

camelCase("this_is_an_example") --thisIsAnExample

camelCase("var") --var

Goodluck! You can find a list of all the challenges here or a github version here.

Answer!
local function camelCase(s)
  local words = {}
  for i, v in pairs(string.split(s,"_")) do --grab all the words separated with a _ underscore
    if i > 1 then  --we don't wanna capitalize the first letter
      table.insert(words, v:sub(1,1):upper()..v:sub(2)) --we take the first character, uppercase, and add the rest. Then I insert to the table
    end
  end
  return table.concat(words,"") --just concat everything inside of the table
end
20 Likes

Made a version using gsub that is pretty fast as well as staying readable:

local function camelCase(s)
	return string.gsub(s, "_%a+", function(word)
		local first = string.sub(word, 2, 2)
		local rest = string.sub(word, 3)
		return string.upper(first) .. rest
	end)
end
5 Likes

This can be done quite simply with string.gsub

local function _tocamel(s)
	return string.upper(string.sub(s,1,1))..string.sub(s,2)
end
local function tocamel(s)
	return (string.gsub(s,"_(%w+)",_tocamel))
end
print(tocamel"this_should_work") --> thisShouldWork
2 Likes

in the spirit of golf

s:gsub("_(.)",s.upper)
12 Likes

no scala? well bud code huh

1 Like

sorry starmaq, shoudlve explicitly stated you wanted it in scala :expressionless:
extractors 4 evor

1 Like

not the shortest but it works like a charm :sunglasses:

Code
local function camelCase(s)
	local sep = string.split(s,"_")
	local strs = {}
	for i, v in ipairs(sep) do
		if i ~= 1 then
			local firstletter = string.sub(v,1,1)
			local upper = string.gsub(v,"^%l",string.upper(firstletter))
			table.insert(strs, upper)
		else
			table.insert(strs, v)
		end
	end
	print(table.concat(strs,""))
end

camelCase("snake_case")
camelCase("this_is_an_example")
camelCase("var")
2 Likes

decided to make the worst solution i could think of while still keeping it relatively readable. this is the result. (also no gsub because gsub is too easy)

solution
local function toCamelCase(inp)
	local t = setmetatable(inp:split("_"),{__index = table})
	t:foreach(function(k,v)
		if k > 1 then
			t[k] = v:sub(1,1):upper()..v:sub(2,#v)
		end	
	end)
	return t:concat()
end
print(toCamelCase("hello_there_starmaq")) --> "helloThereStarmaq"
1 Like

Not exactly the nicest looking code but it’s me first try

function camelCase(s)
	local CurrentWord
	for Num,Word in pairs(string.split(s,"_"))do
		CurrentWord = Num == 1 and string.lower(Word) or (CurrentWord..string.gsub(Word,"^%l", string.upper))
	end
	return CurrentWord
end
camelCase("snake_case") --snakeCase

camelCase("this_is_an_example") --thisIsAnExample

camelCase("var") --var
3 Likes

Alright. Heres a solution without the string library’s functions gsub, split, or upper.

function simpleStyleConversion (str)
	local new_string = ''
	
	local upper_flag=0
	local function upperCaseNext()
		upper_flag=-32
		return ''
	end
	
	for i=1, #str do
		local byte = string.byte(str, i) + upper_flag
		upper_flag = 0
		
		new_string = new_string .. (byte~=95 and string.char(byte) or upperCaseNext())
	end
	return new_string
end
3 Likes

Split by every character, find and remove any underscores and uppercase the character after it.

local function camelCase(givenString)
    local characterArray = string.split(givenString, ".");

    while (true) do
        local index = table.find(characterArray, "_");
        
        if (index) then
            characterArray[index + 1] = string.upper(characterArray[index + 1]);
            table.remove(characterArray, index);
        else
            return table.concat(characterArray, "");
        end
    end
end
4 Likes
local s = "snake_case_eee_case_case_case"

local function camelCase(s)
	local g = s:gsub("%_(%w+)", function(part) local before, after = part:sub(1,1), part:sub(2)  return before:upper()..after end)
	return g
end

print(camelCase(s))
2 Likes

Here’s my attempt:

local function camelCase(str)

    local strings = {}
    local snakeCaseString = str

    for i, splitted in ipairs(snakeCaseString:split("_")) do
        table.insert(strings, i, splitted)
    end

    local camelCaseConvert = ""

    -- Upper and Combine
    for i, str in ipairs(strings) do
        if i ~= 1 then
            str = str:gsub("^%l", string.upper)
        end
        camelCaseConvert = camelCaseConvert .. str
    end

    return camelCaseConvert

end

print(camelCase("i_am_gaming")) --> iAmGaming
2 Likes

Hi, i just made this, very simple to read and works perfectly

local function toCamel(text: string)
    if not text:match("_%a") then 
        return
    end

    local toUpper = text:gsub("_%a", string.upper)
    local Result = toUpper:gsub("_", "")

    return Result
end

local Formated = toCamel("snake_case") --snakeCase
print(Formated)

print(toCamel("hello_there_how_are_yall_doing")) --helloThereHowAreYallDoing
1 Like

Hello, I wanted to try this out and here is the solution I thought of:

local function ConvertUglyToCamelCase(String)
	return(string.gsub(String, "_%a", function(Letter)
		return string.upper(string.sub(Letter, 2,2))
	end))
end

print(ConvertUglyToCamelCase 'lol_case_nob_sjdj_xd')


print(ConvertUglyToCamelCase 'ugly_case_convert_me_before_I_get_my_eyes_hurt')

print(ConvertUglyToCamelCase'xd_s')

print (  ConvertUglyToCamelCase 'lol' )
3 Likes

One of my favourite challenges so far, here’s my take at it.

local function camelCase(str)
	local splitString = str:split("_") 
	if (#splitString < 2) then return end -- dont do anything if the string had do underscores in it

	for k, v in ipairs(splitString) do
		-- Don't do anything at the first index (camelCase)
		if (k > 1) then
			splitString[k] = v:sub(1, 1):upper() .. v:sub(2, #v)
		end
	end
	
	return table.concat(splitString, "")
end

print(camelCase("snake_snake_snake_snake"))
3 Likes

My first try and my first version. (Without gsub)


local function camelCase(input: string) : string
	input = string.split(input, '_');
	for index: number = 2, #input do
		input[index] = string.upper(input[index]:sub(1, 1)) .. input[index]:sub(2, input[index]:len()); 
	end
	return table.concat(input);
end

Examples

print(camelCase("this_is_an_example")) --> thisIsAnExample
1 Like
local function camel_case(s) -- :P
	local after = false
	local new = ""

	for letter in string.gmatch(s, ".") do
		if letter == "_" then
			after = true
		elseif after then
			new = new .. string.upper(letter)
			after = false
		else
			new = new .. letter
		end
	end
	
	return new
end

print(camel_case("hello_world_lol"))

Y’all string wizards doing this in two lines

1 Like

Well, I’m late to this… anyways, I had my own take, and it’s similar to yours!

local function camelCase(input)

local split = string.split(input,"_")
local final = {}

for i,v in pairs(split) do
	if i == 1 then 
		table.insert(final,v)
	else
		local findReplace = string.sub(v,1,1)
		local finalString = string.gsub(v,findReplace,string.upper(findReplace))
		print(finalString)
		table.insert(final,finalString)
	   end
   end
   return table.concat(final,"")
end

print(camelCase("snake_yes"))
print(camelCase("snake_yes_person_thingy"))
1 Like