I want to find “dog” in it
and obviously it will find dog in it 3 times
but instead of replacing it 3 times how do I only replace 1 instance of “dog” with " " aka nothing
Well first I would convert the string to a table using string.split. Then I would replace the first instance of the word and breaking when I find a match:
local myString = "I like dog dog dog"
local function buildString(String)
local stringTable= string.split(String, " ") -- Creates a new index in the table for each space, returns {“I”, “like”, “dog”, “dog”, “dog”}
for i, word in pairs(stringTable) do -- Loop through table
if table.find(stringTable, word, i + 1) then -- Checks if the current word is found in the table, starting from the next index in the table (see string library in roblox api)
table.remove(stringTable, i) -- If there’s a match, remove it from the table
break -- Break to prevent additional removing
end
end
local newString = ""
for i, word in pairs(stringTable) do
newString = newString.. " "..word -- Creates a new string (it just took out the first appearance of any repeated word)
end
return newString
end
print(buildString(myString)) -- Should print “I like dog dog”
This is probably not the most efficient way of doing this.
I added comments so you can see what I’m doing in each line. It’s not looking out for any specific word, but it searches for any word that is repeated.
Well in that case, you can just check to see if the word in the current iteration is “dog” by just using an and if statement:
local myString = "I like dog dog dog"
local function buildString(String)
local stringTable= string.split(String, " ") -- Creates a new index in the table for each space, returns {“I”, “like”, “dog”, “dog”, “dog”}
for i, word in pairs(stringTable) do -- Loop through table
if table.find(stringTable, word, i + 1) and word.lower() == “dog” then -- Checks if the current word is found in the table, starting from the next index in the table (see string library in roblox api)
table.remove(stringTable, i) -- If there’s a match, remove it from the table
break -- Break to prevent additional removing
end
end
local newString = ""
for i, word in pairs(stringTable) do
newString = newString.. " "..word -- Creates a new string (it just took out the first appearance of any repeated word)
end
return newString
end
print(buildString(myString)) -- Should print “I like dog dog”
local myString = "I like dog dog dog"
local finalString = myString:match(".+dog "):gsub("dog ", "") .. myString:match("dog (.+)")
print(finalString) -- "I like dog dog"