Capitalize first letter of a string

this should’ve been really trivial to do but I have no idea how to wrap my head around it :sweat_smile:

how would I capitalize only the first letter of a string?

1 Like

found a solution:

local function capitalize_first_letter(text)
    return string.upper(string.sub(text, 0, 1)) .. string.sub(text, 2)
end

print(capitalize_first_letter("test"))
print(capitalize_first_letter("hi"))
print(capitalize_first_letter("hello"))
> "Test"
> "Hi"
> "Hello"

would’ve been nicer if string.upper had an optional init argument, like with string.find

Although your solution works, I feel it would be more neat using string.gsub and not having to create a new function using string.sub twice.

would’ve been nicer if string.upper had an optional init argument, like with string.find

string.gsub pretty much does this for you.

Like this

print( ('hi'):gsub('^%l', string.upper) ) --> Hi

%l means any character (%w, %S, %C etc… are also possible options). Adding the ^ at the beginning means that it should strictly effect the first character of the string.

Read more here if you’re interested in learning more about patterns like these:
http://lua-users.org/wiki/StringRecipes

2 Likes

Just so you’re aware a first argument of 0 to string.sub is unnecessary.

local String = "Test."
print(string.sub(String, 1, 1)) --T
local Clock = os.clock()
local String = "hello world!"

for _ = 1, 100000 do --0.017
	String = string.upper(string.sub(String, 1, 1))..string.lower(string.sub(String, 2))
end

print(os.clock() - Clock)
local Clock = os.clock()
local String = "hello world!"

for _ = 1, 100000 do --0.012
	String = string.gsub(String, "^.", string.upper)
end

print(os.clock() - Clock)

Roughly 30% more efficient.

2 Likes