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
6 years ago
Edited 6 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 — 6y
0
You can pass dictionaries through gsub EpicMetatableMoment 1444 — 6y

1 answer

Log in to vote
1
Answered by 6 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 — 6y
0
thank you so much RiotGUI 15 — 6y
Ad

Answer this question