Replace A Letter İn A String With Given Number

so im trying to make system that founds letter on a string with given number and replace it with another letter
for example i have a string that says "Hello!"then i want to replace its second letter with “H” so it should be like “HHllo!” how can i do that?

if you dont understand it im sorry my english isnt good

1 Like

I think you can do that :

string.gsub("e", "H")

I hope that was helpful ! :wink:
EDIT : string

1 Like

yes i can replace it that way but i want to replace it with given number not with a given letter

1 Like
local str = "Hello"
string.gsub(str, "e", "H")

I don’t really understand what you mean sorry … :sweat_smile:

You can use %a to detect strings.
You can use %d to detect numbers.

local stg = "Hello"
print(string.gsub(stg,"H",6))

To replace an entire string with numbers -

local stg = "word"
print(stg:gsub("%a+",1))

To replace letters from 1 index to another index:

local word = "Hello"
print(string.sub(word,1,4))

If you want to replace, say, the second letter of a string, do this:

local str = "Hello"
local newStr = string.sub(str, 1, 1) .. "H" .. string.sub(str, 3)
print(newStr) -- HHllo
1 Like

ok i try explain it better
yes i want to replace second letter of “Hello!” but i want to do it with a number
so that means if the number was 4 then i want to replace the fourth letter of “Hello!” with H

local word = "Hello"
local new = word:gsub("l",4)
print(new) --> "He44o"


local new2 = word:gsub(string.sub(word,4),8)
print(new2) -->  Hel8  

local num = 4
local str = "Hello!"
str = string.sub(str, 1, num-1).."H"..string.sub(str, num+1, #str)

sorry for not responding for long i was trying to figure out what you guys did and i finally understand it!
Thanks for the all replys

1 Like
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("Hello!", 2, "H"))
2 Likes