How to format strings in Java

后端 未结 8 1925
执笔经年
执笔经年 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条回答
  •  有刺的猬
    2020-11-22 11:00

    I wrote this function it does just the right thing. Interpolate a word starting with $ with the value of the variable of the same name.

    private static String interpol1(String x){
        Field[] ffield =  Main.class.getDeclaredFields();
        String[] test = x.split(" ") ;
        for (String v : test ) {
            for ( Field n: ffield ) {
                if(v.startsWith("$") && ( n.getName().equals(v.substring(1))  )){
                    try {
                        x = x.replace("$" + v.substring(1), String.valueOf( n.get(null)));
                    }catch (Exception e){
                        System.out.println("");
                    }
                }
            }
        }
        return x;
    }
    

提交回复
热议问题