-1

I'm trying to printf a String where field width is given by a variable, rather than hard coded in the format string. Plus, I want printf to start the string on a new line.

System.out.printf("\r\n>%-32s<", "Hello World");    //works ok

output (the initial newline doesn't show up in the stackoverflow formatter):

>Hello World                     <

The cheverons here are not command line prompts, but are to visually confirm the width of the field.

However, if I try constructing the format string dynamically, using as far as I can see the correct escape sequences, I can't get the initial return & new line characters to actually cause a return & new line.

import java.util.*;

class DynamicFormatStringTest {

  private static final int TEXT_LENGTH = 32;

  public static void main(String[] args){    
    String myFormat = "\\r\\n>%-" + TEXT_LENGTH+ "s<";
    //System.out.println(myFormat);                           //prints \r\n>%-32s<
    System.out.printf(myFormat, "Hello World");
  }

}

output:

\r\n>Hello World                     <

I'm getting the literal \r\n output.

Could anyone tell me what the correct technique is?

twisted
  • 742
  • 2
  • 11
  • 19
  • Possible duplicate of [How to format strings in Java](http://stackoverflow.com/questions/6431933/how-to-format-strings-in-java) – DimaSan Dec 26 '16 at 14:01
  • 1
    I don't get it ... why do you use `\\r\\n` even though you knew that `\r\n` works correctly? – Tom Dec 26 '16 at 14:05

1 Answers1

0

Don't hardcode "\r\n", that's only a correct line separator for Windows. Use %n. Like,

String myFormat = "%n>%-" + TEXT_LENGTH+ "s<";
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249