Call reset on ByteArrayOutputStream to generate a clean new string
ps.printf("there is a %s from %d %s", "flip", 5, "haters");baos.reset(); //need reset to write new stringps.printf("there are %d % from a %", 2, "kisses", "girl");System.out.println(baos.toString());
The output will be there are 2 kisses from a girl
Both solutions workto simulate printf, but in a different way.For instance, to convert a value to a hex string, you have the 2 following solutions:
with format()
, closest to sprintf()
:
final static String HexChars = "0123456789abcdef";public static String getHexQuad(long v) {String ret;if(v > 0xffff) ret = getHexQuad(v >> 16); else ret = "";ret += String.format("%c%c%c%c",HexChars.charAt((int) ((v >> 12) & 0x0f)),HexChars.charAt((int) ((v >> 8) & 0x0f)),HexChars.charAt((int) ((v >> 4) & 0x0f)),HexChars.charAt((int) ( v & 0x0f)));return ret;}
with replace(char oldchar , char newchar)
, somewhat faster but pretty limited:
...ret += "ABCD".replace('A', HexChars.charAt((int) ((v >> 12) & 0x0f))).replace('B', HexChars.charAt((int) ((v >> 8) & 0x0f))).replace('C', HexChars.charAt((int) ((v >> 4) & 0x0f))).replace('D', HexChars.charAt((int) ( v & 0x0f)));...
There is a third solution consisting of just adding the char to ret
one by one (char are numbers that add to each other!) such as in:
...ret += HexChars.charAt((int) ((v >> 12) & 0x0f)));ret += HexChars.charAt((int) ((v >> 8) & 0x0f)));...
...but that'd be really ugly.