Return a specific value of an array function using just one line?

Silly beginner question I know, but I couldn’t find anything, is there any way to put say the last two lines of this on to one line?

Dim x as String = "Hello_World"

Dim y() as string = x.split("_")
x = y(0)

ie So I don’t have to declare another array variable (y) just to retrieve one part of the array? Basically I want to have a way of doing a bit like the function .left() but it stop string at a specific character instead of a character count.

you can extend this string class

it is just a own method you would put into a modul.
then you have something like this to use

Dim x as String = "Hello_World"
Dim y as String = x.Magic()

more or less the same as

Dim y as String = Magic(x)

You can also look at String.NthField

Your code would look like:

Dim x as String = "Hello_World"

x = x.NthField("_", 1)
1 Like

Why not:

Dim x as string = x.split("_").ItemAt(0)

Maybe in another language out of the box as ItemAt doesn’t exist or via an extends on a global method as Markus mentioned (just tweaked so it looks as Oliver asked)?

Public Function ItemAt(Extends s() as String, index as Integer) As String
  Return s(index)
End Function

I’m not sure how performant that would be but vs splitting the line and not going via a method but for ui stuff its fine.

Remember though, split once if its a large data set as putting the same spit on multiple lines will incur a performance hit to split the same thing over and over.

i guess that would create an error if there is no underscore in the string,
that would mean every call need a try catch around.

Split returns the whole string in the first entry if there is no split so it would work in the example shown, however moving above 0 could be an issue, as it would in a split line solution, but yes, at least you could check for array length before you did any work on the array in a split line solution. Of course with the Extends method, you could add checking in there and return an empty string on a failure if that was acceptable in the situation.

1 Like

Doesn’t Wayne’s answer deal with OP’s question and deal with values other than 0. You can move above 0 (say 3) and Wayne’s solution

x = x.NthField("_", 4)

would just return an empty string.

You have to overcome the slight mental awkwardness that Xojo for the most part has settled on zero-based schemes but NthField is one-based.

1 Like

How about

Var x As String = "Hello_World"
x = x.Left(x.indexOf("_"))
1 Like