How can I get the base (last part) of a URL?
I have URL's like the following:
www.abc.def.xxx
www.abc.xxx
ww开发者_如何学编程w.abc.def.ghi.yy
I need to find some way of getting the base "xxx" or "yy" when the URL is different. Can anyone think of a way I can do this with c#
You could split it on .
:
string url = "www.abc.def.ghi.yy";
string lastPart = url.Split(new char[] {'.'}).Last()
Or using Regex:
Regex exp = new Regex(@".*\.");
string lastPart = exp.Replace("a.a.a.a.xxx", "");
Or just being stupid:
string lastPart = new string("www.abc.def.ghi.yy".ToCharArray().Reverse().TakeWhile(i => i != '.').Reverse().ToArray());
You'd probably be best off using a regular expression for this but one simple way to do it is like this:
String str = "www.abc.def.xxx";
int lastPosition = str.LastIndexOf(".");
String baseURL = str.Substring(lastPosition + 1, str.Length - lastPosition - 1);
精彩评论