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.
As 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, 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())
CodePudding user response:
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!"
CodePudding user response:
It looks like you may be looking for optional parameters for a function. Try taking a look at Vitalii's answer here : Optional Parameters in Java