简体   繁体   中英

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", ie it does not remove the slash. How could I remove it?

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

尝试:

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

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.

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

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

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 .

什么是关于"/AuditReport".Replace("/","")

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);

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.

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