开发者

Fetching a segment of the URL in the address bar

This is what I tried:

string myURL= "http://mysite.com/articles/healthrelated";
String idStr = myURL.Substring(myURL.LastIndexOf('/') + 1);

I need to fetch "healthrelated" ie the text after the last slash in the URL. Now the problem is that my URL can also be like :

"http://mysite.com/articles/healthrelated/"   

ie "a Slash" at the end of that text too. Now the last slash becomes the one AFTER "healthrelated" and so the result I get using

String idStr = myURL.Substring(myURL.LastIndexOf('/') + 1);

is empty string..

what should my开发者_C百科 code be like so I always get that text "healthrelated" no matter if there's a slash in the end or not. I just need to fetch that text somehow.


Try this.

var lastSegment = url
    .Split(new string[]{"/"}, StringSplitOptions.RemoveEmptyEntries)
    .ToList()
    .Last();


Why don't you use Uri class of .NET and use segments property:

http://msdn.microsoft.com/en-us/library/system.uri.segments.aspx


What you can do in this situation is either using REGEX (which I'm not an expert on, but I'm shure other ppl here are ;) ) or a simple:

string[] urlParts = myURL.Split('/');

and take the last string in this array.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜