I\'m having a issue trying to figure out this. I need to \"fix\" some links, here is an example:
string s = @"www.site.com/link/index.php?REMOVETHISHERE";
s = s.Remove( s.LastIndexOf('?') );
//Now s will be simply "www.site.com/link/index.php"
should do it
Use string.split
.
string URL = "www.site.com/link/index.php?REMOVETHISHERE"
var parts = URL.Split('?');
Then parts[0]
will contain "www.site.com/link/index.php" and parts[1]
will contain "REMOVETHISHERE". You can then use which ever part you want.
You should add checks to make sure that there are two parts before trying to access the 2nd element of the array. You could (for example) check that the string contains "?" before trying to call Split
.
To remove last "?" and everything after it:
string input = @"www.site.com/link/index.php?REMOVETHISHERE";
input = input.Remove(input.LastIndexOf('?'));
OR
string input = @"www.site.com/link/index.php?REMOVETHISHERE";
input = input.Substring(0, input.LastIndexOf('?'));
Now the output will be:
www.site.com/link/index.php
Although a properly crafted string operation will work, the more general way to extract partial URI information is to use the System.Uri type which has methods which encapsulate these operations, e.g.
var uri = new Uri("http://www.site.com/link/index.php?REMOVETHISHERE");
var part = uri.GetLeftPart(UriPartial.Path);
This will convey the intent of your code more clearly and you'll be re-using a current implementation which is known to work.
The System.Uri
constructor will throw an exception if the string does not represent a valid URI, but you will anyway probably want to invoke some other behavior in your program if an invalid URI has been encountered. To detect an invalid URI you can either catch the exception or use one of the TryCreate() overloads.