Java - Append quotes to strings in an array and join strings in an array

前端 未结 7 716
后悔当初
后悔当初 2020-12-13 00:04

I would like to append double quotes to strings in an array and then later join them as a single string (retaining the quotes). Is there any String library which does this?

相关标签:
7条回答
  • 2020-12-13 00:43

    A more generic way would be sth. like:

    private static class QuoteFunction<F> {
        char quote;
    
        public QuoteFunction(char quote) {
            super();
            this.quote = quote;
        }
    
        Function<F, String> func = new Function<F,String>() {
            @Override
            public String apply(F s) {
                return new StringBuilder(s.toString().length()+2).append(quote).append(s).append(quote).toString();
            }
        };
    
        public Function<F, String> getFunction() {
            return func;
        }
    }
    

    ... call it via the following function

    public static <F> String asString(Iterable<F> lst, String delimiter, Character quote) {
        QuoteFunction<F> quoteFunc = new QuoteFunction<F>(quote);
        Joiner joiner = Joiner.on(delimiter).skipNulls();
        return joiner.join(Iterables.transform(lst, quoteFunc.getFunction()));
    }
    
    0 讨论(0)
提交回复
热议问题