SubString function in vb.net Exception call

FromIp

contains "192.168.1.1"

. I want to get the last number, but I cannot figure out what is wrong here:


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

      

+1


source to share


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


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


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

      

instead

FromIP.Text.LastIndexOf(".") 

      

and

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

      

- the last parameter instead of

FromIP.TextLength

      

+1


source


As far as I remember, the substring takes Start, Stop as parameters.

So it will be: txt.Substring(IndexOf, txt.Length - IndexOf)

or with just one parameter: Substring (IndexOf + 1)

0


source







All Articles