简体   繁体   中英

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
www.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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM