How to append a newline to StringBuilder

前端 未结 8 675
天涯浪人
天涯浪人 2020-12-04 06:37

I have a StringBuilder object,

StringBuilder result = new StringBuilder();
result.append(someChar);

Now I want to append a newline characte

8条回答
  •  忘掉有多难
    2020-12-04 07:17

    In addition to K.S's response of creating a StringBuilderPlus class and utilising ther adapter pattern to extend a final class, if you make use of generics and return the StringBuilderPlus object in the new append and appendLine methods, you can make use of the StringBuilders many append methods for all different types, while regaining the ability to string string multiple append commands together, as shown below

    public class StringBuilderPlus {
    
        private final StringBuilder stringBuilder;
    
        public StringBuilderPlus() {
            this.stringBuilder = new StringBuilder();
        }
    
        public  StringBuilderPlus append(T t) {
            stringBuilder.append(t);
            return this;
        }
    
        public  StringBuilderPlus appendLine(T t) {
            stringBuilder.append(t).append(System.lineSeparator());
            return this;
        }
    
        @Override
        public String toString() {
            return stringBuilder.toString();
        }
    
        public StringBuilder getStringBuilder() {
            return stringBuilder;
        }
    }
    

    you can then use this exactly like the original StringBuilder class:

    StringBuilderPlus stringBuilder = new StringBuilderPlus();
    stringBuilder.appendLine("test")
        .appendLine('c')
        .appendLine(1)
        .appendLine(1.2)
        .appendLine(1L);
    
    stringBuilder.toString();
    

提交回复
热议问题