hsim
hsim

Reputation: 2080

Efficient way to get part of a string in vb.net

I have to parse a string to obtain a specific value in it.

Here's an example of a string I need to parse: "@MSG 12,9: NINJUTSU"

Here I need to obtain the 12 value. The order of the value will not change, meaning that I will always aim the first number in the string; however the length of the string (12, 9, 58) is variable (but never negative) and the message (NINJUTSU) is also changing.

So far I proceed like this:

Dim tempErrorList As List(Of String) = errorMsg.Split(New Char() {":"}).ToList()

Dim listErr As List(Of String) = tempErrorList(0).Split(New Char() {","}).ToList()

Dim errCode As List(Of String) = listErr(0).Split(New Char() {" "}).ToList()

However I don't like it because of the 3 splits needed to obtain the values. I do not know how I could do it in one shot or fewer operations?

Upvotes: 0

Views: 633

Answers (1)

j.i.h.
j.i.h.

Reputation: 827

Similar to the deleted answer, you could use String.Split like so: errorMsg.Split(" ,:".ToCharArray()), which does what you're doing above but with one function call.

errorMsg.Split(" ,:".ToCharArray())(1) would give you the "12" you need.

Alternatively, you can use combinations of String.SubString() with String.IndexOf(), but the logic can become unwieldy and opaque. String.Split Alternatives (MSDN) gives more details on this approach.

Upvotes: 2

Related Questions