抛出异常的vb.net中的SubString函数

时间:2008-12-12 11:58:20

标签: vb.net string

FromIp包含"192.168.1.1"。我想得到最后一个号码,但我不知道这里有什么问题:


    Dim str As String
    str = FromIP.Text.Substring(FromIP.Text.LastIndexOf("."), FromIP.Text.Length).ToString()
    MessageBox.Show(FromIP.Text.Length)

4 个答案:

答案 0 :(得分:5)

Eduardo已经给出了获得子串的正确方法 - 我的回答将解释为什么现有的失败。

String.Substring(int, int)占据起始位置和计数。你基本上是在说,“从第9位转到10个字符”。文档明确声明它将抛出:

  

ArgumentOutOfRangeException [if]

     

startIndex加长度表示a   位置不在此实例中。

     

-OR -

     

startIndex或length小于   零。

答案 1 :(得分:4)

经过测试的代码:

    Dim FromIp As String = "192.168.1.1"
    Dim str As String
    str = FromIp.Substring(FromIp.LastIndexOf(".") + 1).ToString()
    MessageBox.Show(str)
  • 您必须将1添加到LastIndexOf以跳过点
  • 当你想要所有其余的字符串
  • 时,不需要放置Substring的长度

但是这个重构的代码会更好用:

    Dim FromIp As String = "192.168.1.1"
    Dim IpPart As String() = FromIp.Split(".")
    MessageBox.Show(IpPart(3))

答案 2 :(得分:1)

FromIP.Text.LastIndexOf(".") + 1 

而不是

FromIP.Text.LastIndexOf(".") 

FromIP.TextLength-FromIP.Text.LastIndexOf(".") 

是最后一个参数,而不是

FromIP.TextLength

答案 3 :(得分:0)

据我记得,Substring以Start,Stop为参数。

那样就是:txt.Substring(IndexOf, txt.Length - IndexOf)或只有一个参数:Substring(IndexOf + 1)