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

How do I replace a certain word in a string?

Asked by 9 years ago

I'm making a chat system which is fully functional and I'm currently adding new features to it so it can be better than average. For one of these ideas, I wanted to add an auto correct option. I've tried and tried, but the furthest I can get is literally just doing print(string.find(msg,word)). That returns the incorrectly spelled word, but I have no idea how to actually change it. I have a table that looks like this, which is how the words get corrected (if you can't figure out how it works, leave):

Correct = {{"lpl","lol"},{"lel","lol"}} -- Those are examples so you get the idea

Could somebody please point me in the right direction?

0
Yes, I think the Direction You're looking for is that way --> Vezious 310 — 9y

3 answers

Log in to vote
2
Answered by 8 years ago

string.gsub will work for this, you can search for a word and if it appears you can use string.gsub to replace the pattern (the word) with a string you want. I'm not going to provide code, it should be quite simple.

Ad
Log in to vote
1
Answered by 9 years ago

what i would do is that i would use the values returned by string.find to isolate the two parts of the string surrounding what you're trying to change like so:

local stringtoprocess = "hello, my name is gina and i love motorcycles"
local stringtofind = "gina"

local startvalue,endvalue = string.find(stringtoprocess,stringtofind) --these store the values

--the first of these lines obtains the string starting at the first character and ending one character  before the start value of the word to remove; the second starts one character after the end value and continues to the end of the string (thus string.len)
local firststring = string.sub(stringtoprocess,1,startvalue-1)
local secondstring = string.sub(stringtoprocess,endvalue+1,string.len(stringtoprocess))

so now things become very simple and all you need is this:

local stringtoinsert = "..."
local processedstring = firststring..stringtoinsert ..secondstring 

when processedstring is printed, this is the result:

hello, my name is ... and i love motorcycles

good luck and happy coding!

Log in to vote
0
Answered by 9 years ago

Try using string.gsub (s, pattern, repl [, n]).

http://wiki.roblox.com/index.php?title=String_manipulation#string.gsub

Answer this question