-1

I need to print out formulas like "A{i}+B{i}+C{i}" for some i so it would look like A0+B0+C0 (for example). Is there any easy way to do it without regex?

I tried making regex but it's a bit inconvenient for this expression.

2

1 Answer 1

6

You could use the String format to get a formatted output for some i as below (Ordinary indexing):

String.format("A%d+B%d+C%d", i, i, i)

But this can further shortened by using Relative indexing (argument from the previous format specifier is re-used)

String.format("A%d+B%<d+C%<d", i)

or Explicit Indexing (explicitly specifying the argument index to be used)

String.format("A%1$d+B%1$d+C%1$d", i)

Refer docs for more information

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

1 Comment

Feels like a cleaner take on this is String.format("A%d+B%<d+C%<d", i). < is format-ese for 'previous argument'. Avoids having to repeat i 3 times. Starting with JDK.. 23 probably, STR."A\{i}+B\{i}+C\{i}" will do it.

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.