Ron
Ron

Reputation: 1931

how to extract string from certain position

I am struggling to find a solution in string manipulation - I am trying to extract a certain part of the string element after the '=' character - say for ex.

 dim s as string = "/mysite/secondary.aspx?id=1005" 

I am trying to get the string after the "=" and just to grab the 1005. I tried indexof and split, but i am not sure where i am going wrong. Any help, please?

Here is what i did:

 Dim lnk As String = "/mysite/secondary.aspx?id=1005"  
 Dim id As Long = lnk.IndexOf("=")   
 Dim part As String = lnk.Substring(id + 1, 4)

Thanks

Upvotes: 2

Views: 816

Answers (4)

Sam Axe
Sam Axe

Reputation: 33738

Dim tUriPath As String = "/mysite/secondary.aspx?id=1005"
Dim tURI As Uri = New Uri("dummy://example.com" & tUriPath)
Dim tIdValue As String = System.Web.HttpUtility.ParseQueryString(tUri.Query)("id")

Upvotes: 5

Icarus
Icarus

Reputation: 63956

If you try string.Split with '=' you'll get 1005 on the first element of the array and the /mysite/secondary.aspx?id= on the 0th position.

But if this is just a regular URL coming from an http request.

You could possibly do Request.QueryString("id") and it will return 1005;

Borrowing code from Boo...

Dim tUriPath As String = "/mysite/secondary.aspx?id=1005"
Dim tURI As Uri = New Uri("dummy://example.com" & tUriPath)
Dim tIdValue As String = System.Web.HttpUtility.ParseQueryString(tUri.Query)

Dim theIntYouWant as String= System.Web.HttpUtility.ParseQueryString(tUri.Query)("id")

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245419

Here's a very simple example. Obviously it relies on very specific conditions:

Dim afterEquals As String = s.Split("="c)(1)

You would probably want something slightly more robust (checking to make sure more than one string was returned from Split, etc.).

Upvotes: 1

JaredPar
JaredPar

Reputation: 754615

Try the following

Dim index = s.IndexOf("="C)
Dim value = s.Substring(index + 1)  

This will put "1005" into value

Upvotes: 6

Related Questions