简体   繁体   中英

Java - make string flag for system.out.format change on input

I'm trying to set the flag of the

System.out.format("%s", string);

so the s has variable allocated size associated with it.

For example: I want

System.out.format("%MyVars", string);

Where MyVar would be a variable dependent on the size of a particular list in the program

Where as of now I can only have static numbers like:

System.out.format("%5s", string);

How would I do this?

Why don't you use string concatenation to achieve your desired format?

Below code snippet my help:-

int num = 5;
System.out.format("%" + num + "." + string.length() + "S", string);

You can do this using the below snippet:

String string = "abc";
int size =5;
System.out.format("%d%s", size, string);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM