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

How to find word used in string from a table and then replaces the words with new one?

Asked by
RiotGUI 15
5 years ago
Edited 5 years ago

How to make a script that finds words used in a string from a table and then replaces the words with new one?

Here's my attempt:

local stringtofind = {'are', 'you'}
local stringtoprocess = 'i think you are cool'
local startvalue,endvalue = string.find(stringtoprocess,stringtofind)
local firststring = string.sub(stringtoprocess,1,startvalue-1)
local secondstring = string.sub(stringtoprocess,endvalue+1,string.len(stringtoprocess))
local stringtoinsert = "you're"
local processedstring = firststring .. stringtoinsert ..secondstring

print(processedstring) -- i want it to print "i think you're cool"

Any help?

0
string.gsub(string, thingToReplace, thingToReplaceItWith) should do what you're looking for fredfishy 833 — 5y
0
You can pass dictionaries through gsub EpicMetatableMoment 1444 — 5y

1 answer

Log in to vote
1
Answered by 5 years ago

You can pass dictionaries through gsub.

Example code:

local replacers = {
  ["hello"] = "ok",
  ["cool"] = "epic"
}

local old = "hello this is cool"
local new = old:gsub("%S+", replacers)

print(old)
print(new)

Output: >> hello this is cool >> ok this is epic

In this case the string new is old but it replaced all words in the dictionary replacers with each index's value. e.g. "hello" is now "ok" and "cool" is now "epic"

0
now this is epic Elixcore 1337 — 5y
0
thank you so much RiotGUI 15 — 5y
Ad

Answer this question