Dynamically formatting a string

Posted by TofuBeer on Stack Overflow See other posts from Stack Overflow or by TofuBeer
Published on 2010-03-23T06:54:50Z Indexed on 2010/03/23 7:03 UTC
Read the original article Hit count: 301

Filed under:

Before I wander off and roll my own I was wondering if anyone knows of a way to do the following sort of thing...

Currently I am using MessageFormat to create some strings. I now have the requirement that some of those strings will 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 a couple ways I can think of creating the format string, such as having 1 String per number of arguments (there is a finite number of them so this is practical, but seems bad), or build the string dynamically (there are a lot of them so this could be slow).

Any other suggestions?

© Stack Overflow or respective owner

Related posts about java