How to remove slash from string in C#

Liker777 picture Liker777 · Nov 25, 2011 · Viewed 9.6k times · Source

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?

Answer

LukeH picture LukeH · Nov 25, 2011

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('/');