简体   繁体   中英

What is the best way to remove characters at start of a string in c#?

Considering I have a string like this:

var myStr = @"\r\n test";

What is the best way to remove the characters like \\r and \\n (carriage feed characters) and empty characters

One way I can think of is

var trimmedString = myStr.Replace("\r\n", "").Trim();

What is the most elegant way to do this ?

It's hard to tell if you want the carriage return and line feed characters removed or if you want the literal string: "\\r\\n" removed.

The code you have posted:

new string (@"\r\n  test")

Is not even valid syntax. If you want a string literal the syntax is:

var someString = @"\r\n some value";

The @ Means that you are literally including the string: "\\r\\n" in the output, this means it will not output the escape characters \\r\\n which is carriage return and line feed.

If you want to remove the specific string "\\r\\n" you can use String.Replace like you were doing, I have cleaned up your code a bit and removed some redundancies:

var trimmedString = @"\r\n  test".Replace(@"\r\n", "");

If you actually want to remove the escape characters from the beginning of the string you need to remove the @ symbol so its no longer a string literal, then you can use the TrimStart() method of a string:

var trimmedString = "\r\n  test".TrimStart();

TrimStart() accepts a char[] parameter that details the specific characters you want to remove. However if you do not pass any parameter to TrimStart() it will automatically remove whitespace characters from the beginning of the string.

Fiddle here

Assuming that you wish to remove "raw" escape sequences from your string, you can generalize regex-based approach as follows:

var trimmed = Regex.Replace(original, @"^(\\[rntv]|\s)*", "");

This removes verbatim \\n , \\r , \\t , and \\v sequences with optional whitespaces at the beginning of the string. Note that \\ at the beginning is doubled inside a verbatim @"..." string literal, meaning that the regex is going to match an escape sequence, not the character it represents.

Demo.

最好的答案是使用正则表达式。

new Regex(@"(^\s+").Replace("\r\n BLah blah blah   ","")

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