Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to split string into arrays of duplicates?

Say I have a string: $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ul ! I want to split it into: { "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$", "u", "l", " ", "!", " " } This is my current code:

local function splitIntoDuplicates(str)
	local match = str:sub(1, 1)
	local i = 2
	local j = 1
	
	local duplicates = {""}
	
	while i <= #str do
		if str:sub(i, i) == match then
			duplicates[j] ..= str:sub(i, i)
		else
			match = str:sub(i, i)
			
			j += 1
			duplicates[j] = ""
		end
		
		i += 1
	end
	
	return duplicates
end

It works for the first part, but then everything else just becomes empty strings: {                     [1] = "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$",                     [2] = "",                     [3] = "",                     [4] = " ",                     [5] = ""                  } The code is horribly hacky in the first place. Is there a better method, perhaps with string matching?

1 answer

✓ Accepted answer

This hasn't really been tested thoroughly, but here's what a wrote:

EDIT: Updated code to work with "magic characters"

function splitString(str, index)
    local magic_characters = {"%", "+", "-", "*", "(", ")", "{", "}", "^", "[", "]", ".", "$"}
    index = index or 1
    if index <= #str then
        if table.find(magic_characters, firstCharacter) then
            firstCharacter = "%" .. firstCharacter
        end

        local firstCharacter = str:sub(index, index)
        local Start, End = str:find(firstCharacter .. "+", index)

        if index == 1 then
            return {str:sub(Start, End), splitString(str, End + 1)}
        elseif End <= #str then
            return str:sub(Start, End), splitString(str, End + 1)
        end
    end
end

It's a solution based on tail calls. Usage and result:

local result = splitString("$$$$$$$$$$llllrrruu!aaaa bbb")
-- result: {"$$$$$$$$$$", "llll", "rrr", "uu", "!", "aaaa", " ", "bbb"}

This discussion is preserved as it was. New answers, comments, and votes are closed.