How to split a string when ever a specific character is met?

This is difficult for me to explain so I will just give an example.

Let’s say the character to split at is a space:
Input: “the dog ran”
output: {“the”, “dog”, “ran”}

Or the character to split at is a colon:
Input: “the:dog:ran”
output: {“the”, “dog”, “ran”}

1 Like

try using string.split I think it will do what you want.

1 Like

I use this function to split string:

-- Compatibility: Lua-5.0
function Split(str, delim, maxNb)
   -- Eliminate bad cases...
   if string.find(str, delim) == nil then
      return { str }
   end
   if maxNb == nil or maxNb < 1 then
      maxNb = 0    -- No limit
   end
   local result = {}
   local pat = "(.-)" .. delim .. "()"
   local nb = 0
   local lastPos
   for part, pos in string.gfind(str, pat) do
      nb = nb + 1
      result[nb] = part
      lastPos = pos
      if nb == maxNb then
         break
      end
   end
   -- Handle the last field
   if nb ~= maxNb then
      result[nb + 1] = string.sub(str, lastPos)
   end
   return result
end

I got it from this website, feel free to check it out as there are different use cases for different types of split functions.


@RamJoT There are no exact split functions in Lua, it has to be manually made.

1 Like

Roblox added its own string.split function that returns a table

local str = "Hey,There,Person"
local strTable = str:split(",")
for _,str in pairs(strTable) do
   print(str)
end

11 Likes

string.split is a roblox addition to the string library, and its probably the best way to do this.

2 Likes

Whoops! I’ve been so outdated in the string library that I didn’t even notice that until now. Was this an addition within the past year? Don’t believe I remember seeing it when I first began looking into an admin system.

Yes.

Release notes when it was added-

1 Like