接触Java时间不长,最近遇到个问题,格式化字符串的在.net中 string result=  string.format("我的名字:{0},性别:{1},年龄:{2}","BetterChaner","男","24");result结果为:我的名字:BetterChaner,性别:男,年龄:24我在JAVA用 string result=  string.format("我的名字:{0},性别:{1},年龄:{2}","BetterChaner","男","24")result结果为:我的名字:{0},性别:{1},年龄:{2}我想得到的是像.net那样的,请问应该怎么写? 不是replace("{0}","BetterChaner")这样的!!!

解决方案 »

  1.   

    jdk1.5以后的可以用:
    MessageFormat.format("我的名字:{0},性别:{1},年龄:{2}","BetterChaner","男","24");
      

  2.   

    楼主。。改为如下即可。Java中采用跟C语言一样的占位符,字符串用%s,数字%d。。String result= "我的名字:%s ,性别:%s,年龄:%d";
    System.out.println(String.format(result, "小明","男",20));
      

  3.   

    楼上提到的方法也是可以的。
    String result= "我的名字:%s ,性别:%s,年龄:%d";
    System.out.println(String.format(result, "小明","男",20));

    String str = "我的名字:{0} ,性别:{1},年龄:{2}";
    System.out.println(MessageFormat.format(str, "小明","男",20));
      

  4.   

    String result= "我的名字:%s ,性别:%s,年龄:%s";
    System.out.println(String.format(result, "小明","男",20)); %s是占位符,ls写错了,没有%d这个占位符
    同时用MessageFormat也是可以的,正如ls所写