网站做302重定向会怎么样,西安网站建设中企建站,wordpress主题颜色,网站页面做多宽一、前言 刚开始从.net的转向java的时候总觉得 String.format 用得不习惯#xff0c;希望格式模版会这样 {0}, this is {1}s cat.{1},this is {0}s dog. 而不是 %1$s,this is %2$ss cat.%2$s,this is %1$ss dog.…一、前言 刚开始从.net的转向java的时候总觉得 String.format 用得不习惯希望格式模版会这样 {0}, this is {1}s cat.{1},this is {0}s dog. 而不是 %1$s,this is %2$ss cat.%2$s,this is %1$ss dog. 。后来发现 java.text.MessageFormat.format 可以满足我这个小小的愿望。 二、静态方法 java.text.MessageFormat.format 方法定义 String MessageFormat.format(String fmt, Object...args) 入参fmt为MessageFormat模式参数。 三、MessageFormat模式 格式 ArgumentIndex[,FormatType[,FormatStyle]] ArgumentIndex 是从0开始的入参位置索引。 FormatType 指定使用不同的Format子类对入参进行格式化处理。值范围如下 number调用NumberFormat进行格式化 date调用DateFormat进行格式化 time调用DateFormat进行格式化 choice调用ChoiceFormat进行格式化 FormatType 设置FormatType中使用的格式化样式。值范围如下 shortmediumlongfullintegercurrencypercentSubformPattern(子格式模式形如#.##) 注意 FormatType 和 FormatStyle 主要用于对日期时间、数字、百分比等进行格式化。 示例——将数字1.23格式为1.2 double num 1.23;
String str MessageFormat.format({0,number,#.#}, num); 四、MessageFormat注意点 1. 两个单引号才表示一个单引号仅写一个单引号将被忽略。 2. 单引号会使其后面的占位符均失效导致直接输出占位符。 MessageFormat.format({0}{1}, 1, 2); // 结果12
MessageFormat.format({0}{1}, 1, 2); // 结果{0}{1}
MessageFormat.format({0}{1}, 1, 2); // 结果{0} 因此可以用于输出左花括号(单写左花括号会报错而单写右花括号将正常输出) MessageFormat.format({{0}}, 2); // 结果{2 因此前言中的示例应该写为 {0}, this is {1}s cat.{1},this is {0}s dog. 五、类层级关系 |-- java.text.MessageFormat 顶层抽象类java.text.Format—| |--java.text.ChoiceFormat |--java.text.NumberFormat—| | |--java.text.DecimalFormat | |--java.text.DateFormat—java.text.SimpleDateFormat 1. DecimalFormat 用于格式化十进制实数。通过格式字符串来自定义格式化类型舍入方式为half-even(四舍五入)。 格式化模式 正数子模式;负数子模式 如 0.00;-0.00 简写为 0.00 。 模式中的占位符 0 代表该为位为数字若不存在则用0填充 # 代表该为位为数字 , 代表分隔符, 如模式为 #,# 那么格式化10时会返回1,0 2. ChoiceFormat 相当于以数字为键字符串为值的键值对。分别使用一组double类型的数组作为键一组String类型的数组作为值两数组相同索引值的元素作为一对。 示例——基本用法 double[] limit {0,1,3};
String[] format {hello0, hello1, hello3};
ChoiceFormat cf new ChoiceFormat(limit, format);
for(int i 0; i 4; i){System.out.println(cf.format(i));
}
/* 输出* hello0* hello1* hello0* hello3*/ 注意当找不到对应的键值对时则使用第一或最后一对键值对。 示例——结合MessageFormat使用 double[] limit {0, 1};
String[] format {Hello0, Hello1{1}};
ChoiceFormat cf new ChoiceFormat(limit, format);
MessageFormat mf new MessageFormat({0});
mf.setFormatByArgumentIndex(0, cf);
for (int i 0; i 2; i){System.out.println(mf.format(new Object[]{new Integer(i), new Integer(i1)}));
}
/* 输出* Hello0* Hello12*/ 六、性能问题 由于静态方法 MessageFormat.format 内部是 public static String format(String pattern, Object ... arguments)
{ MessageFormat temp new MessageFormat(pattern); return temp.format(arguments);
} 因此若要多次格式同一个模式的字符串那么创建一个MessageFormat实例在执行格式化操作比较好些。 七、总结 对于简单的格式化或字符串组装 MessageFormat.format方法 使用更方便些但要格式化处理更丰富的话要是用 String.format方法 吧 尊重原创转载请注明来自http://www.cnblogs.com/fsjohnhuang/p/4095059.html ^_^肥仔John 八、参考 http://zqc-0101.iteye.com/blog/114014 转载于:https://www.cnblogs.com/fsjohnhuang/p/4095059.html