How can we prepend strings with StringBuilder?

后端 未结 12 2147
一整个雨季
一整个雨季 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:37

    Here's what you can do If you want to prepend using Java's StringBuilder class:

    StringBuilder str = new StringBuilder();
    str.Insert(0, "text");
    
    0 讨论(0)
  • You could try an extension method:

    /// <summary>
    /// kind of a dopey little one-off for StringBuffer, but 
    /// an example where you can get crazy with extension methods
    /// </summary>
    public static void Prepend(this StringBuilder sb, string s)
    {
        sb.Insert(0, s);
    }
    
    StringBuilder sb = new StringBuilder("World!");
    sb.Prepend("Hello "); // Hello World!
    
    0 讨论(0)
  • 2020-12-24 00:43

    Try using Insert()

    StringBuilder MyStringBuilder = new StringBuilder("World!");
    MyStringBuilder.Insert(0,"Hello "); // Hello World!
    
    0 讨论(0)
  • 2020-12-24 00:45

    If I understand you correctly, the insert method looks like it'll do what you want. Just insert the string at offset 0.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-24 00:46

    This should work:

    aStringBuilder = "newText" + aStringBuilder; 
    
    0 讨论(0)
提交回复
热议问题