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

[SOLVED] How would I split a string if I know where it should be split?

Asked by 5 years ago
Edited 5 years ago

Hey guys, the question sounds:

How to split a string if I know the part where it should be split?

For example, I get a string "16-11-2018;12:20". How would I get "16-11-2018" and "12:20" if I know the string (resp. character) it will always be split by? (In this case ";")

Thanks in advance! Any tip is appreciated!

(Bonus question: How would I do the same if I would know the characters position? E.g. in this case, by the 11th character (which is the ";"))

0
string.sub https://developer.roblox.com/articles/Lua-Libraries/string#string.sub, togheter with string.find or something like that User#20388 0 — 5y

1 answer

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

X Y Problem

First, prefacing this with a small explanation of the X/Y problem. I have reason to believe that you have a solution in mind for your problem, and you want us to help you realise your solution rather than solve your problem. That's great, in fact that's almost the only reason I'm answering this question because at least you engaged your brain.

That said...

String Patterns

If you know how a string should look, a great way to capture parts of a string is by using Lua string patterns. These describe a format of a string, and parts that you want to get out of it, and allows Lua to do the heavy lifting for you. As an example, the simplest pattern you probably want is (.*);(.*).

day, time = yourString:match("(.*);(.*)")

Substrings

This said, if you know the position of the delimiter you can just get a substring with string.sub. To get that, you want something like

day = yourString:sub(1, delimiter-1)
time = yourString:sub(delimiter+1, -1)

The X/Y problem (again)

Why is your input formatted that way? Why is it a string? Is it possible that you could get it formatted in JSON, or stored as a table rather than a string? This would save you a lot of trouble.

For reference:

0
there are valid reasons to need to split a string at a character, not much of an X-Y problem User#22604 1 — 5y
0
I actually have time and date from API in JSON, but basically it is like 16-11-2018;12:28 Doge_Brigade 94 — 5y
1
xD, anyways, as I said above - I got the JSON, but I just wanna know how to actually split it - One table querie into two. Doge_Brigade 94 — 5y
Ad

Answer this question