Splitting a string at a certain amount of characters in?

Hello! I am trying to split a string at directly 20 characters in. For example:

Our string will be Hello World, and I want to split it by the first 5 characters to give us the strings Hello and World.

How would I accomplish this?

You can use this function,

function string:split(delimiter)
  local result = { }
  local from  = 1
  local delim_from, delim_to = string.find( self, delimiter, from  )
  while delim_from do
    table.insert( result, string.sub( self, from , delim_from-1 ) )
    from  = delim_to + 1
    delim_from, delim_to = string.find( self, delimiter, from  )
  end
  table.insert( result, string.sub( self, from  ) )
  return result
end

Source: string.split in lua (github.com)

local string = "Hello World"
print(string:split(" ")[1])

You can split strings with this

Iā€™m not sure how you would split it at a certain number of characters, but you can use string.split() to split it with specific seperator characters.

local String = "HEY,BAH,YEE"
local Strings = string.split(String,",")
print(Strings[1], Strings[2], Strings[3])

Use string.sub() string Documentation. All you need to do is provide it a string to split, a starting point, and an end point. Also, you can leave out the last argument to get a string from character ā€˜iā€™ to the end of the string. For your case:

local stringToSplit = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
local first20 = string.sub(stringToSplit, 1, 20)
--first20 = "ABCDEFGHIJKLMNOPQRST" (aka the first 20 characters)
6 Likes