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?

Alexander Ivanchenko
29.2k6 gold badges29 silver badges53 bronze badges
asked Aug 28, 2022 at 8:49
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.

answered Aug 28, 2022 at 11:23
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");
answered Aug 28, 2022 at 8:53
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

answered Aug 30, 2022 at 23:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.