Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert StringBuilder#AppendFormat to java

Tags:

java

c#

I am converting C# code to Java, and I came across this line (where i is an int).

sb.AppendFormat("\\u{0:X04}", i);

From what I can see, Java does not have an appendFormat method on its StringBuilder.

How would I go about converting this?

EDIT:

I see that AppendFormat is just a combination of append and String.format. How would I convert \\u{0:X04} to Java's String.format?

like image 374
jlars62 Avatar asked Apr 28 '15 16:04

jlars62


3 Answers

The java.util.Formatter class has a zero-argument constructor which automatically wraps a StringBuilder:

Formatter formatter = new Formatter();
formatter.format("\\u%04x", i);

// ...

String finalText = formatter.toString();

// Or, if you want to be explicit about it:
//StringBuilder sb = (StringBuilder) formatter.out();
//String finalText = sb.toString();
like image 140
VGR Avatar answered Sep 21 '22 00:09

VGR


String.format() may do the job for you. So in turn say:

sb.append(String.format("\\u{0:X04}", i));
like image 33
Mordechai Avatar answered Sep 21 '22 00:09

Mordechai


Most of the answers contains little errors (two 0 instead of one, C# format leaved in Java code).

Here is working snipped:

sb.append(String.format("\\u%04X", 0xfcc));

Regarding comments: C# specifier \\u{0:X04} and Java specifier \\u%04X both produce numbers in format \uXXXX where X are upper case hex digits (when you use small x you will get lower case hex digits), so it matters.

like image 45
csharpfolk Avatar answered Sep 22 '22 00:09

csharpfolk