Samantha J T Star
Samantha J T Star

Reputation: 32758

How can I remove some characters from a C# string?

I have the string:

http://127.0.0.1:96/Cambia3

The number 96 could be anything from 75 to 125.

Is there a simple way that I could remove this number to get:

http://127.0.0.1/Cambia3

Upvotes: 1

Views: 274

Answers (5)

pieter.lowie
pieter.lowie

Reputation: 108

For simply removing it would always use this:

string ip = "http://127.0.0.1:96/Cambia3";
ip = ip.Replace(":96", string.Empty);

If needed later you can always reuse this to replace the port.

Upvotes: 0

V4Vendetta
V4Vendetta

Reputation: 38200

Hey you can try something on these lines

UriBuilder uri = new UriBuilder("http://127.0.0.1:96/Cambia3");
uri.Port =-1;            
string portlessurl = uri.Uri.AbsoluteUri; // Output -- http://127.0.0.1/Cambia3

Upvotes: 0

Ghyath Serhal
Ghyath Serhal

Reputation: 7632

You can use something like the below code

string str = "http://127.0.0.1:96/Cambia3";
int index1 = str.IndexOf(':', 7);
int index2 = str.IndexOf('/', 7);

str.Remove(index1, index2 - index1);

Upvotes: 1

Jason
Jason

Reputation: 15931

convert to a URI and then pull out the information you are interested in

var ip= new Uri("http://127.0.0.1:96/Cambia3");
var withoutPort = string.Format("{0}://{1}/{2}", ip.Scheme, ip.Host, ip.PathAndQuery);

Upvotes: 5

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

Strings are immutable - you can't change them - but you can create new one from pieces of old one.

In your case do not use string manipulation - Uri and UriBuilder classes should be used when changing Urls.

Sample:

var builder=new UriBuilder("http://127.0.0.1:96/Cambia3");
builder.Port = 80;
Console.WriteLine(builder.Uri.AbsoluteUri);

Upvotes: 1

Related Questions