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 ";"))
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...
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("(.*);(.*)")
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)
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:
JSONEncode
to turn a table into a stringJSONDecode
to get a table from a JSON-encoded string.