开发者

A string replacement question with C#

How do I remove string in bold within following url where q= is fixed parameter?

http://abc.com/qwe.aspx?q=DIEYeGJgNwvPSJ32ic1sY5x1ZYjOZTQZD9mjWl2EQJ8=&am开发者_JS百科p;u=/foo/boo/kb

Thanks.


it is pretty simple. I use System.Uri class to parse the url, then remove the q query string parameter, and then build a new url without this parameter:

var url = new Uri("http://abc.com/qwe.aspx?q=DIEYeGJgNwvPSJ32ic1sY5x1ZYjOZTQZD9mjWl2EQJ8=&u=/foo/boo/kb");
var query = HttpUtility.ParseQueryString(url.Query);
query.Remove("q");
UriBuilder ub = new UriBuilder(url);
ub.Query = query.ToString();
var result = ub.Uri.ToString();

Now result holds value: http://abc.com/qwe.aspx?u=/foo/boo/kb.


input = Regex.Replace(input, "q=[^&]+", "") would be one way to do it.


Are the positions fixed? You can do one IndexOf("q=") and IndexOf("u=") and use SubString twice to remove the part. An other way would be to use regular expressions.


Maybe this URL comes from some request, meaning you've that query string in the HttpRequest instance, associated to HttpContext.

In this case, you can always remove "q" query string parameter just by calling HttpContext.Current.Request.QueryString.Remove("q");

Another solution would be the one suggested by Alex.


if Q is a fixed parameter....

str = str.Replace("q=DIEYeGJgNwvPSJ32ic1sY5x1ZYjOZTQZD9mjWl2EQJ8=", "");

Otherwise I would do:

var qa = Request.QueryString;
qa.Remove("q");
var queryString = qa.ToString();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜