6

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?

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

(+1) but the same lib has ArrayUtils.toObject(..) to convert the primitive array to the wrapper ;)
the array is actually String so no issue at all. I'll go give it a try and see how it does - thanks.
1

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).

1 Comment

interesting, don't want to add a new dependency to the project, but I'll take a deeper look at it.
1

You can use the String#join method from Java 8 and onwards, which will allow you to join strings with the given delimiter.

String.join(" OR ", "a", "b", "c") 

Comments

0

I think the simplest solution is writing a quick function that runs through the arguments in a for loop, appending “ OR ” + arg[i] to a StringBuilder, (with a special case for the first argument), then returning the StringBuilder's toString() value. How's this?

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.