Substring not sub stringing string, or rather, substring not working as it should
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?
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.
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).
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("_", "")