jlars62
jlars62

Reputation: 7353

Convert StringBuilder#AppendFormat to java

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?

Upvotes: 7

Views: 9002

Answers (5)

Bogdan Mart
Bogdan Mart

Reputation: 498

Other answers haw a flow that intermediate string is being created. Except accepted answer, but it asumes that we don't already have StringBuilder. And yes we can use Formatter INSTEAD of SB. But in many cases in code we receive SB from outside, so we can wrap it into formatter.

Correct answer that have full correspondence to provided C# code is:

// sb.AppendFormat("\\u{0:X04}", i);
Formatter fmt = new Formatter(sb);
fmt.format("\\u%04x", i);

Data would be appended to end of string builder directly. No intermediate string is created. You can also specify locale if needed.

Later applies if we feed to Formatter not String builder, but arbitrary Appendable, like text file.

We don't need to mange lifetime of formatter directly( close it), if we would manage lifetime of writer (if that's not SB but file). If we pass in Writter and don't use that variable anymore -- we would need to close() Fromatter.

Upvotes: 0

csharpfolk
csharpfolk

Reputation: 4280

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.

Upvotes: 3

Dave Doknjas
Dave Doknjas

Reputation: 6542

You need a combination of 'append' and 'String.format', remembering to adjust the format specifier for Java:

sb.append(String.format("\\u%004X", i));

Upvotes: 1

VGR
VGR

Reputation: 44308

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();

Upvotes: 6

Mordechai
Mordechai

Reputation: 16224

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

sb.append(String.format("\\u{0:X04}", i));

Upvotes: 3

Related Questions