How to get a letter of a string?

local function swapChar(string, char, with)
    return string:sub(1, char - 1) .. with .. string:sub(char + 1)
end

print(swapChar("11111", 2, "2")) --> 12111

I will go try this, I’ll mark it the solution if it works

Just a quick question, will this work if n was 1?

if n = 1 then it would replace the first character

“21111111111111111111111”

1 Like

It doesn’t do that, it instead add 2 after the 1st character, also making the string 13 characters not 12

I meant to quote Bones not Seargent I don’t know why it did that

well i see the issue with his code
edit: @avodey did it properly

local String = "111" 
local n = 1 -- Position to replace
local ReplaceWith = "2"

local Result = string.sub(String, 1, n - 1) .. ReplaceWith .. string.sub(String, n + 1, -1)
print(Result) --> 211

i think it would be easier to just specify which occurrence i want to replace instead of specifying position
if i had a string like this “123414914104412351351” and i want to replace the 3rd “1”, then i would need to figure out the position just so i could use a swapChar function.

The reply he gave with a function should work

local function replace(word: string, pos: number, letter: char): string
    local t = string.split(word, "")
    t[pos] = letter
    return table.concat(t, "")
end

print(replace("111111111111", 1, "2")) -- 211111111111

This is find first occurrence …

local str = "hello world"
local letter = "o"

local position = string.find(str, letter)

if position then
	print(letter .." is at position: ".. position)
end

There is a world of things you can do with a string. Maybe it would be better to just say what you are doing fully and not have us looking for a position…

I have no idea why I didn’t try this yet, but it works!

1 Like