SubString function in vb.net Exception call
4 answers
Tested code:
Dim FromIp As String = "192.168.1.1"
Dim str As String
str = FromIp.Substring(FromIp.LastIndexOf(".") + 1).ToString()
MessageBox.Show(str)
- You must add 1 to LastIndexOf to skip point
- No need to set the length of the substring if you want all other strings
But this refactored code will perform better:
Dim FromIp As String = "192.168.1.1"
Dim IpPart As String() = FromIp.Split(".")
MessageBox.Show(IpPart(3))
+4
source to share
Eduardo gave the correct way to get the substring - my answer here will explain why the existing one fails.
String.Substring(int, int)
takes start position and counter. You basically say, "Go from position 9 to 10 characters." The documentation explicitly states that it will throw:
ArgumentOutOfRangeException [if]
startIndex plus length points to positions not in this instance.
-or -
startIndex or length less than zero.
+5
source to share