從C#中的字符串末尾刪除回車符和換行符 (Removing carriage return and new-line from the end of a string in c#)


問題描述

從C#中的字符串末尾刪除回車符和換行符 (Removing carriage return and new‑line from the end of a string in c#)

How do I remove the carriage return character (\r) and the new line character(\n) from the end of a string?

‑‑‑‑‑

參考解法

方法 1:

This will trim off any combination of carriage returns and newlines from the end of s:

s = s.TrimEnd(new char[] { '\r', '\n' });

Edit: Or as JP kindly points out, you can spell that more succinctly as:

s = s.TrimEnd('\r', '\n');

方法 2:

This should work ...

var tst = "12345\n\n\r\n\r\r";
var res = tst.TrimEnd( '\r', '\n' );

方法 3:

String temp = s.Replace("\r\n","").Trim();

s being the original string.  (Note capitals)

方法 4:

If you are using multiple platforms you are safer using this method.

value.TrimEnd(System.Environment.NewLine.ToCharArray());

It will account for different newline and carriage‑return characters.

方法 5:

s.TrimEnd();

The above is all I needed to remove '\r\n' from the end of my string.

The upvoted answer seems wrong to me.  Firstly, it didn't work when I tried, secondly, if it did work I would expect that s.TrimEnd('\r', '\n') would only remove either a '\r' or a '\n', so I'd have to run it over my string twice ‑ once for when '\n' was at the end and the second time for when '\r' was at the end (now that the '\n' was removed). 

(by AvikRichieHindleJP AliotoCrash893Alex Wiesemartinp999)

參考文件

  1. Removing carriage return and new‑line from the end of a string in c# (CC BY‑SA 3.0/4.0)

#newline #string #carriage-return #C#






相關問題

如何格式化電子郵件中的字符串以便 Outlook 打印換行符? (How do I format a String in an email so Outlook will print the line breaks?)

contentEditable поле для захавання новых радкоў пры ўваходзе ў базу дадзеных (contentEditable field to maintain newlines upon database entry)

換行符 (newline character(s))

grep 如何匹配一些字母或行尾 (grep how to match some letters OR end of line)

Trong Python, có thể thoát các ký tự dòng mới khi in một chuỗi không? (In Python, is it possible to escape newline characters when printing a string?)

在 SWIFT 中遇到逗號時將字符串換行 (Break string to newline when meeting a comma in SWIFT)

行尾的'^ M'字符 ('^M' character at end of lines)

從C#中的字符串末尾刪除回車符和換行符 (Removing carriage return and new-line from the end of a string in c#)

新線路和瀏覽器/操作系統兼容性 (New lines and browser/OS compatability)

如何使用 grep 查找單詞後兩個字符之間的所有內容,而不輸出整行? (How do I find everything between two characters after a word using grep, without outputting the entire line?)

在 Perl 中寫入文件的問題 (Issues writing to a file in Perl)

在 for 循環中每 7 行換行一次 (Newline every 7 lines within a for loop)







留言討論