Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically formatting a string

Tags:

java

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?

like image 319
TofuBeer Avatar asked Mar 23 '10 06:03

TofuBeer


2 Answers

Unless, I'm missing something this is plain old join. Until Java 7 gets String.join (no joke) there are some implementations around like Apache commons lang StringUtils.join.

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

The only problem is that is does not work on primtive int[] arrays directly.

like image 132
Thomas Jung Avatar answered Sep 30 '22 04:09

Thomas Jung


using Dollar should be simple:

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

where $(1, n) is a range object wrapper (there are wrappers for Collections, arrays, CharSequences, etc).

like image 22
dfa Avatar answered Sep 30 '22 06:09

dfa