4

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?

Ajean
  • 5,528
  • 14
  • 46
  • 69
Liker777
  • 2,156
  • 4
  • 18
  • 25

8 Answers8

18

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('/');
LukeH
  • 263,068
  • 57
  • 365
  • 409
6

Try:

var r = rep.SysName.Remove(0, 1);
Abbas
  • 14,186
  • 6
  • 41
  • 72
4

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.

Wouter de Kort
  • 39,090
  • 12
  • 84
  • 103
2

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

var r = rep.SysName.Remove(0, 1);
Daniel Rose
  • 17,233
  • 9
  • 65
  • 88
0

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.

Shahin Dohan
  • 6,149
  • 3
  • 41
  • 58
0

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

rekire
  • 47,260
  • 30
  • 167
  • 264
0

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);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

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.

Fischermaen
  • 12,238
  • 2
  • 39
  • 56