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

Split a string when a certain character is found?

Asked by
DevChris 235 Moderation Voter
8 years ago

For example: local levelInfo = "1_1" is the string I'm using. How would I split the string so I get two variables for the first 1 and the second 1, because there is a '_' in the middle of it? Not sure this is possible with string.sub because the 1 may be a two-digit number and I don't think it can detect when there is a certain character.

2 answers

Log in to vote
3
Answered by
Discern 1007 Moderation Voter
8 years ago

You can use string.find to find where the underscore is and then split the string using string.sub.

string.find returns at what character position a pattern is found. A pattern can be any string (in your case it would be _). Once the pattern is found, you can use string.sub to get the substrings using the information from string.find as your divider.

local levelInfo = "1_1"

local divider = string.find(levelInfo, "_") --levelInfo is your string and "_" is your divider. The variable "divider" is now the numerical position of the pattern "_" in the string,
local substring1 = string.sub(levelInfo, 1, divider - 1) --I'm assuming you know what string.sub does since you mentioned it in your question.. You have to subtract one from "divider" because "divider" would equal the position of "_" and you want everything before that.
local substring2 = string.sub(levelInfo, divider + 1, string.len(levelInfo)) --Use the same thing as the line above, but divider + 1 is the starting position (add 1 because divider is equal to "_") and the ending position is the total number of characters inside the string (received from string.len).

Here is more information on string.find.

If I helped you out, be sure to accept my answer!

Ad
Log in to vote
1
Answered by
1waffle1 2908 Trusted Badge of Merit Moderation Voter Community Moderator
8 years ago

A better method is to use string.match

local levelInfo="1_1"
local a,b=levelInfo:match("(.*)_(.*)")
print(a)
print(b)
0
I've got my answer but thanks anyway DevChris 235 — 8y

Answer this question