tags:

views:

1461

answers:

4

FromIp contains "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)
+4  A: 

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 the dot
  • There no need put the lenght of the Substring when you want all the rest of the string

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))
Eduardo Molteni
Alternatively it would be: Dim IpPart As String() = FromIp.Split(".")
Tomalak
You are right, can't get the VB6 syntax out of my head
Eduardo Molteni
Just to be picky .. you could goDim IpPart As String = FromIp.Split(".")(3)
spacemonkeys
A: 

As far as I remember, Substring takes Start,Stop as parameters.

So that would be: txt.Substring(IndexOf, txt.Length - IndexOf) or just with one parameter: Substring(IndexOf + 1)

Marcel J.
A: 

Hi, FromIP.Text.LastIndexOf(".")+1 instead of FromIP.Text.LastIndexOf(".") and FromIP.TextLength-FromIP.Text.LastIndexOf(".") is the last parameter instead of FromIP.TextLength

lakshmanaraj
+4  A: 

Eduardo has given the correct way of getting the substring - my answer here will just explain why the existing one fails.

String.Substring(int, int) takes a starting position and a count. You're basically saying, "Go from position 9 for 10 characters". The documentation explicitly states it will throw:

ArgumentOutOfRangeException [if]

startIndex plus length indicates a position not within this instance.

-or-

startIndex or length is less than zero.

Jon Skeet