Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
sprintf for Java is callled String.format, a better string replace

PHP example:

$location = 'tree';
$format = 'There are 5 monkeys in the %s';
echo sprintf($format, $location);
#output: There are 5 monkeys in the tree

Java String.format

String monkeyHome = "tree";

//System output
System.out.println(String.format("There are 5 monkeys in the %s", monkeyHome));

//new variable
String monkeySong = String.format("There are 5 monkeys in the %s", monkeyHome);
You can also use it with multiple variables to replace. This is very usefull for replacing text in text templates:

String monkeyHome = "tree";
int monkeyFamSize = 5;

//System output
System.out.println(String.format("There are %d monkeys in the %s", monkeyFamSize, monkeyHome));

//new variable
String monkeySong = String.format("There are %d monkeys in the %s", monkeyFamSize, monkeyHome);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.