How can we prepend strings with StringBuilder?

后端 未结 12 2339
一整个雨季
一整个雨季 2020-12-24 00:22

I know we can append strings using StringBuilder. Is there a way we can prepend strings (i.e. add strings in front of a string) using StringBuilder

12条回答
  •  被撕碎了的回忆
    2020-12-24 00:46

    You could create an extension for StringBuilder yourself with a simple class:

    namespace Application.Code.Helpers
    {
        public static class StringBuilderExtensions
        {
            #region Methods
    
            public static void Prepend(this StringBuilder sb, string value)
            {
                sb.Insert(0, value);
            }
    
            public static void PrependLine(this StringBuilder sb, string value)
            {
                sb.Insert(0, value + Environment.NewLine);
            }
    
            #endregion
        }
    }
    

    Then, just add:

    using Application.Code.Helpers;
    

    To the top of any class that you want to use the StringBuilder in and any time you use intelli-sense with a StringBuilder variable, the Prepend and PrependLine methods will show up. Just remember that when you use Prepend, you will need to Prepend in reverse order than if you were Appending.

提交回复
热议问题