2

In C we can specify the amount to space to leave in printf , any similar way to do this in java?

For example

int space=6;
char message[10]="hi";

printf("%*s",space,message);

will print

    hi
Jesper
  • 202,709
  • 46
  • 318
  • 350
Sainath S.R
  • 3,074
  • 9
  • 41
  • 72
  • AFAIK you'd have to dynamically build a sequence of whitespace for the indentation. You could create method yourself that mimicks that behavior, which shouldn't be that hard. – Thomas Jun 23 '15 at 14:02
  • I know but i need to solve certain problems under constrains where writing too many methods etc aint allowed, I'ms urprised that C has this Out of the box and not java – Sainath S.R Jun 23 '15 at 14:04

1 Answers1

7

Create the format string dynamically:

int space = 6;
System.out.printf("%" + space + "s", "hi");
Jesper
  • 202,709
  • 46
  • 318
  • 350
  • `println` doesn't take a format string in Java. If you want the output in a `String`, use `String result = String.format("%" + space + "s", message);` – Jesper Jun 23 '15 at 14:06
  • No. The first argument is the format string. It's not printed literally (if you use `printf`). (Try it out!). The format string does not need to be a string literal. – Jesper Jun 23 '15 at 14:07
  • If you prefer to, you could also build the format string with format: `System.out.printf(String.format("%%%ds", space), "hi");`. – Keppil Jun 23 '15 at 14:12
  • thanks a lot , now i understand clearly , but in c instead of (%5s...) we can use (%*s,...) and pass the formating value also as an argument , that is not possible in java 's System.out.printf.........right? – Sainath S.R Jun 23 '15 at 15:00
  • No, but it's not much harder to do the same thing in Java, as you can see. – Jesper Jun 23 '15 at 15:12