Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How would I replace multiple letters in a string with different letters?

Asked by
Loot_O 42
4 years ago
Edited 4 years ago

Last post, I figured out how I could replace a letter with another letter using gsub. Try running this in the command bar:

local str = "Hello there! How are you doing? I'm feeling great today!" 
local changedString = str:gsub("a", "z") 
print(changedString)

Now it would print that string, but all the A's get replaced by Z. I do know how to do that, but how would I replace multiple letters? For example, I turn the A's to a Z, the B's to a Y, and the E's to an X.

Here are 2 things I have tried:

local str = "Hello there! How are you doing? I'm feeling great today!" 
local changedString = str:gsub("a", "z") 
changedString = str:gsub("b", "y") 
changedString = str:gsub("e", "x") 
print(changedString)

Now this wouldn't work because every time it would change the changeString thing, it would overwrite it with the normal string, but a letter replaced by another. And only 1 letter replaced. Other thing I tried:

local str = "Hello there! How are you doing? I'm feeling great today!" 
local changedString = str:gsub("a", "z") 
changedString = changedString:gsub("b", "y") 
changedString = changedString:gsub("e", "x") 
print(changedString)

Now this would replace multiple letters, yes. But say like in a line, the script would replace all the E's with a Y, then in the next line, it would replace all Y's with an O, and I want the changed letters not to change again. Thanks!

0
So basically, you don't want a letter that's been subbed to be subbed again? Gey4Jesus69 2705 — 4y
0
Yes. Loot_O 42 — 4y
0
print(string.gsub('best friend','best','bad')) xD D D D D D D DDDDD D D D D D Dddd greatneil80 2647 — 4y
0
u could just use sub before it, x = string.sub(string,2,4) gsub(x,'x D D D D', ' x D D D D D D DD') greatneil80 2647 — 4y

1 answer

Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

Try doing this all in one line (i don't know if this can work):

local str = "Hello there! How are you doing? I'm feeling great today!"

str = ((str:gsub("a","z")):gsub("b", "y")):gsub("e","x")

print(str) -- will print "Hxllo thxrx! How zrx you doing? I'm fxxling grxzt todzy!"

Explanation: They will gsub according to their positions, and you can immediately replace the changed string's characters to another. Hope this helps! (I'm not really sure how you stop the already changed ones to changing again)

Ad

Answer this question