简体   繁体   中英

How to remove www, http/https and other strings in URL in C#

For Example I have this string

http://www.merriam-webster.com/dictionary/sample

What I want is to return only merriam-webster.com I'm planning to use .Replace() but I think there are better approach for this question.

If you are working for Winforms then

string url = "http://www.merriam-webster.com/dictionary/sample";

UriBuilder ub = new UriBuilder(url);

MessageBox.Show(ub.Host.Replace("www.",""));

and for web,

Get host domain from URL?

How about this

System.Uri uri = new Uri("http://stackoverflow.com/search?q=something");
string uriHost = uri.Host;

?

Answers here don't handle the case like " http://abcwww.com ". Check if the url starts with 'www.' before replacing it.

if (url.StartsWith("www.", StringComparison.OrdinalIgnoreCase))
    url = url.Replace("www.", string.Empty);

You can use this:

        var a = "http://www.merriam-webster.com/dictionary/sample";
        var b = a.Split('.');
        var c = b[1] +"."+ b[2].Remove(3);

You can leverage System.Uri class:

System.Uri uri = new Uri("https://www.google.com/search?q=something");
string uriWithoutScheme = uri.Host + uri.PathAndQuery + uri.Fragment;

Or you can use below:

UriBuilder ub = new UriBuilder("https://www.google.com/search?q=something");
currentValue = ub.Host.Replace("www.", "");

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