Does the string type have any built in Split() functionality?
Hi Root,
Good question, splitting strings is not mentioned on the string docā¦
Itās mentioned that strings are āliteralsā (fixed values), so I think the path forward might involve working directly with arrays of chars.
I noticed some array functions transfer to stringā¦ which isnāt surprising. But I actually donāt see many string functions at all hmm
Iāve added a snippet for one here. Wonāt be 100% most optimal but probably not awful. You can use it like this:
SplitResult1 := "string,to,split".Split(",") # ["string", "to", "split"]
SplitResult2 := "123".Split("") # ["1", "2", "3"]
Nice. I wrote a pretty full set of string functions but didnāt do āSplitā. I need to look over them again and post them as snippets.
I had already written one as well (only tested with a few test-cases):
SplitString(StVal: string, Delimiter: char): []string =
var Words : []string = array{}
var Word : string = ""
var Val: string = StVal + "{Delimiter}"
for (Index := 0..Val.Length):
if (Val[Index] <> Delimiter):
if (Letter := Val[Index]):
set Word += "{Letter}"
else:
if (Word.Length <> 0):
set Words = Words + array{Word}
set Word = ""
return Words
and call like this:
# Test split string:
var SText : string = "test, string,wow, commas"
var Result : []string = SplitString(SText, ',')
for (Item : Result):
Print(Item)
This is fine and all, but thereās tons of built-in string methods that I really like to use in in most well known languages. Hopefully verse authors add this in the future.
Itās not that I canāt code itā¦ Itās more that I would rather have trivial things like this added into the standard library.
But then again, I guess string handling isnāt necessarily that important for game Devs
Do you trim spaces (i.e., is the fourth element of your resulting test array " commas" or ācommasā)?
Probably not worth dealing with, since itās for game development. Itās too easy getting sucked into system development when we need to focus on game development!
Ah it keeps the spacesā¦ good call should probably fix that. And it only splits on one ācharā and not a string of length >= 1. So maybe itās not so good haha. But yeah Iām hoping they expand on there standard library and release a runtime soon.
EDIT: Actually keeping spaces there when splitting on a comma is the expected behavior for most similar functionsā¦ python for example:
$ python
Python 3.10.7 (tags/v3.10.7:6cc6b13, Sep 5 2022, 14:08:36) [MSC v.1933 64 bit (
AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 'test, string,wow, commas'.split(',')
['test', ' string', 'wow', ' commas']
If I was doing system development, Iād add an optional ābTrimā parameter, but we are just making games, so itās probably not worth it.
Also, a lot of languages have some kind of Map function so that you could apply Trim on the resulting array.