Reputation: 905
I'm working on an application where users can select some values previously presented to them, they will always have a specific form like this: userData_North
, userData_South
.
I need the part of the string that is after the _
, so obviously I tried doing a substring like this:
Dim rightString = userDataVar.SubString(userDataVar.IndexOf("_"), userDataVar.Length)
Which I believe gets whatever is after the _
and until the string ends. But it returns Nothing
for some reason. What could I've gotten wrong?
Upvotes: 0
Views: 204
Reputation: 2005
You've mistaken how the Substring works. All you need is the following:
Dim rightString = userDataVar.SubString(userDataVar.IndexOf("_") + 1)
The reason it's returning Nothing
is because you are starting halfway through the string and then asking it to go for the entire length of the string and you are going outside the range of it.
Upvotes: 1
Reputation: 85655
The two parameters to String.Substring
are startIndex
and length
- it looks like you were expecting startIndex' and
endIndex' (ala JavaScript's substring
).
It's actually throwing an ArgumentOutOfRange
exception (as documented in this case), meaning you're probably running with On Error Resume Next
or otherwise hiding exceptions - that always make debugging a lot harder (and isn't really great for production either).
As mentioned by others, there's also convenience method to just get the remaining length which seems appropriate for your use case. Otherwise, you'd need to subtract out the IndexOf
.
As an alternative, you could also consider using String.Split
- especially if you intend to discard the "_" separator (in which case you'd need to +1
your IndexOf
).
Upvotes: 1
Reputation: 7082
You're about to get the North or South?.
Dim userDataVar As String = "userData_South"
Dim startIndex = userDataVar.IndexOf("_")
Dim rightString = userDataVar.Substring(startIndex)
Dim getNorthSouth = rightString.Replace("_", "")
Upvotes: 0