Liker
Liker

Reputation: 2267

How to remove slash from string in C#

I have a string like this: "/AuditReport" It is assigned to variable rep. If I type

var r = rep.SysName.Remove(1, 1);

It returns "/uditReport" instead of desired "AuditReport", i.e. it does not remove the slash. How could I remove it?

Upvotes: 4

Views: 13912

Answers (8)

Shahin Dohan
Shahin Dohan

Reputation: 6907

If you're dealing with a Uri, you can do it this way:

var route = uri.GetComponents(UriComponents.Path, UriFormat.UriEscaped);

It will return for example api/report rather than /api/report.

Upvotes: 0

LukeH
LukeH

Reputation: 269278

String indices in .NET are zero-based. The documentation for Remove states that the first argument is "The zero-based position to begin deleting characters".

string r = rep.SysName.Remove(0, 1);

Alternatively, using Substring is more readable, in my opinion:

string r = rep.SysName.Substring(1);

Or, you could possibly use TrimStart, depending on your requirements. (However, note that if your string starts with multiple successive slashes then TrimStart will remove all of them.)

string r = rep.SysName.TrimStart('/');

Upvotes: 18

Fischermaen
Fischermaen

Reputation: 12458

You have to write var r = rep.SysName.Remove(0, 1);. I guess you have a VisualBasic background (like me :-) ), arrays, strings, etc in C# start with an index of 0 instead of 1 as in some other languages.

Upvotes: 0

Guffa
Guffa

Reputation: 700152

String indexes in .NET is zero based, so:

string r = rep.SysName.Remove(0, 1);

You can also use:

string r = rep.SysName.Substring(1);

Upvotes: 0

rekire
rekire

Reputation: 47945

What is about "/AuditReport".Replace("/","")?

Upvotes: 0

Daniel Rose
Daniel Rose

Reputation: 17638

The index is 0-based, so you are removing the second character. Instead, try

var r = rep.SysName.Remove(0, 1);

Upvotes: 2

Wouter de Kort
Wouter de Kort

Reputation: 39888

You need:

var r = rep.SysName.Remove(0, 1);

The first parameter is the start, the second is the number of characters to remove. (1,1) would remove the second character, not the first.

Upvotes: 4

Abbas
Abbas

Reputation: 14432

Try:

var r = rep.SysName.Remove(0, 1);

Upvotes: 6

Related Questions