[英]SubString function in vb.net throwing Exception
FromIp
contains "192.168.1.1"
. FromIp
包含"192.168.1.1"
。 I want to get the last number, but I can't figure out what's wrong here: 我想获取最后一个数字,但我无法弄清楚这里出了什么问题:
Dim str As String
str = FromIP.Text.Substring(FromIP.Text.LastIndexOf("."), FromIP.Text.Length).ToString()
MessageBox.Show(FromIP.Text.Length)
Eduardo has given the correct way of getting the substring - my answer here will just explain why the existing one fails. 爱德华多(Eduardo)提供了获取子字符串的正确方法-我在这里的回答只会解释为什么现有子字符串会失败。
String.Substring(int, int)
takes a starting position and a count . String.Substring(int, int)
处于起始位置,并且具有count 。 You're basically saying, "Go from position 9 for 10 characters". 您基本上是在说:“从位置9开始10个字符”。 The documentation explicitly states it will throw: 该文档明确声明它将抛出:
ArgumentOutOfRangeException [if] ArgumentOutOfRangeException [如果]
startIndex plus length indicates a position not within this instance. startIndex加上length表示不在此实例中的位置。
-or- -要么-
startIndex or length is less than zero. startIndex或length小于零。
Tested code: 经过测试的代码:
Dim FromIp As String = "192.168.1.1"
Dim str As String
str = FromIp.Substring(FromIp.LastIndexOf(".") + 1).ToString()
MessageBox.Show(str)
But this refactored code will work better: 但是此重构的代码会更好地工作:
Dim FromIp As String = "192.168.1.1"
Dim IpPart As String() = FromIp.Split(".")
MessageBox.Show(IpPart(3))
FromIP.Text.LastIndexOf(".") + 1
instead of 代替
FromIP.Text.LastIndexOf(".")
and 和
FromIP.TextLength-FromIP.Text.LastIndexOf(".")
is the last parameter instead of 是最后一个参数而不是
FromIP.TextLength
As far as I remember, Substring takes Start,Stop as parameters. 据我所知,Substring采用Start,Stop作为参数。
So that would be: txt.Substring(IndexOf, txt.Length - IndexOf)
or just with one parameter: Substring(IndexOf + 1) 因此可能是: txt.Substring(IndexOf, txt.Length - IndexOf)
或仅带有一个参数:Substring(IndexOf + 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.