Dynamic string formatting

Before I wander around and throw my own, I was wondering if anyone knew of a way to do the following:

I am currently using MessageFormat to create some lines. Now I have a requirement that some of these lines have a variable number of arguments.

For example (current code):

MessageFormat.format("{0} OR {1}", array[0], array[1]);

Now I need something like:

// s will have "1 OR 2 OR 3"
String s = format(new int[] { 1, 2, 3 }); 

and

// s will have "1 OR 2 OR 3 OR 4"
String s = format(new int[] { 1, 2, 3, 4 }); 

There are several ways that I can think of creating a format string, for example, having 1 string per number of arguments (there are a finite number of them so that it is practical, but it seems bad), or build a string dynamically (there are a lot of them, so it can be slow) .

Any other suggestions?

+5
source share
3 answers

-, join. Java 7 String.join( ), , Apache commons lang StringUtils.join.

StringUtils.join(new Integer[] { 1, 2, 3, 4 }, "OR");

, primtive int [].

+5

Dollar :

String s1 = $(1, 3).join(" OR ");
String s2 = $(1, 4).join(" OR ");

$(1, n) - ( Collection s, , CharSequence s ..).

+1

, , for, " OR " + arg[i] StringBuilder ( ), StringBuilder toString() . ?

String format(String... args) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < args.length; i++) {
        if (i > 0) {
            sb.append(" OR ");
        }
        sb.append(args[i]);
    }
    return sb.toString();
}
0

All Articles