0

I need a string as follows.

s = "$.vars.start.params.operations.values"

I've tried to write it like this:

String s = "$".concat(".").concat("start").concat(".").concat("params").concat(".").
concat("operations").concat(".").concat("values");

There's a chain of concat operations.

Is there a better way of doing this?

2
  • 3
    "$" + "..." + "..."!? Or just have the plain string since there is nothing dynamic in the string anyway. Or join Commented Aug 28, 2022 at 8:53
  • 1
    What's wrong with "$." + start + "." + params + … (assuming those are actually variables)? Commented Aug 28, 2022 at 8:57

3 Answers 3

2

Never ever use concat like this. It is bound to be less efficient than the code the compiler generates when using +. Even worse, the code as shown (using only String literals) would have been replaced with a single string literal at compile time if you had been using + instead of concat. There is almost never a good reason to use concat (I don't believe I have ever used it, but maybe it could be useful as a method reference in a reduce operation).

In general, unless you are concatenating in a loop, simply using + will get you the most (or at least relatively good) performant code. When you do have a loop, consider using a StringBuilder.

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

Comments

1

It seems like you're looking for Java 8 method String.join(delimiter,elements), which expects a delimiter of type CharSequence as the first argument and varargs of CharSequence elements.

String s = String.join(".", "$", "vars", "start", "params", "operations", "values");

Comments

0

Do you have a reason for using .concat? In this case, you would approach this by using something like "$"+"..." etc.

If you wanted to add a dynamic approach, I would recommend using variables instead. It would look like

String s = variable1 + variable2 + variable; 

If you are looking for something a bit more than there is also the String.join

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.