badmate
badmate

Reputation:

SubString function in vb.net throwing Exception

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)

Upvotes: 1

Views: 3462

Answers (4)

lakshmanaraj
lakshmanaraj

Reputation: 4175

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

instead of

FromIP.Text.LastIndexOf(".") 

and

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

is the last parameter instead of

FromIP.TextLength

Upvotes: 1

Eduardo Molteni
Eduardo Molteni

Reputation: 39413

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))

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500065

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.

Upvotes: 5

Marcel Jackwerth
Marcel Jackwerth

Reputation: 54752

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)

Upvotes: 0

Related Questions