Trim whitespace from the end of a StringBuilder without calling ToString().Trim() and back to a new SB
问题 What is an efficient way to trim whitespace from the end of a StringBuilder without calling ToString().Trim() and back to a new SB new StringBuilder(sb.ToString().Trim()) . 回答1: The following is an extension method, so you can call it like this: sb.TrimEnd(); Also, it returns the SB instance, allowing you to chain other calls ( sb.TrimEnd().AppendLine() ). public static StringBuilder TrimEnd(this StringBuilder sb) { if (sb == null || sb.Length == 0) return sb; int i = sb.Length - 1; for (; i