How to format strings in Java

后端 未结 8 2048
执笔经年
执笔经年 2020-11-22 10:44

Primitive question, but how do I format strings like this:

\"Step {1} of {2}\"

by substituting variables using Java? In C# it\'s

8条回答
  •  萌比男神i
    2020-11-22 11:05

    public class StringFormat {
    
        public static void main(String[] args) {
                Scanner sc=new Scanner(System.in);
                System.out.println("================================");
                for(int i=0;i<3;i++){
                    String s1=sc.next();
                    int x=sc.nextInt();
                    System.out.println(String.format("%-15s%03d",s1,x));
                }
                System.out.println("================================");
    
        }
    }
    

    outpot "================================"
    ved15space123 ved15space123 ved15space123 "================================

    Java solution

    • The "-" is used to left indent

    • The "15" makes the String's minimum length it takes up be 15

    • The "s" (which is a few characters after %) will be substituted by our String
    • The 0 pads our integer with 0s on the left
    • The 3 makes our integer be a minimum length of 3

提交回复
热议问题