0

I have a function which currently only accepts two arguments - a string and a List for arguments.

This function goes ahead, gets a string from a language file. In this language file, I wanted to allow a possiblity to add arguments, which would be filled. Example: "{1} has thanked {2}". The function then goes ahead, and using MessageFormat.format adds the arguments to the message.

I've gotten used to other languages (namely SourcePawn) which support the following syntax:
print("%s has thanked %s", user1, user2)
which replaces the %s tags with the arguments, and I wanted to replicate this in Java. Is there any way to do so?

Desired result would be to make the function work like this:
fillInArguments("Hello {1}! You have {2} unread messages!", user.getName(), user.getUnreadMsgs())

technyk
  • 17
  • 5
  • 1
    Look in to [String.format](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#format(java.lang.String,java.lang.Object...)) with syntax discription [Formatter syntax](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Formatter.html#syntax) – Eritrean Jan 21 '23 at 20:20

1 Answers1

0

You could use String.format like this :

String.format("Hello %s! You have %d unread messages!", user.getName(), user.getUnreadMsgs());

Symbol following "%" will depends of the type of the variable you want to add in the string. see table here https://www.javatpoint.com/java-string-format

But if you directly have the parameters i guess you can also simply use concatenation like this :

"Hello " + user.getName() + "! You have " + user.getUnreadMsgs() + " unread messages!"
loic .B
  • 281
  • 2
  • 11
  • Nicely explained, thanks. The hard-coded paramaters were just a quick code I came up with to explain what I meant, but I'd definitely use the concatenation if I had them set up like that. – technyk Jan 21 '23 at 21:51