在Java编程中格式化字符串,用String类的静态方法String.format():
format(Locale l, String format, Object... args)//使用指定的语言环境、格式字符串和参数返回一个格式化字符串。
format(String format, Object... args)
//使用指定的格式字符串和参数返回一个格式化字符串。
举几个这个方法实用的例子(注释是输出结果):
//案例1long now = System.currentTimeMillis()
String s = String.format("%tR",now) //输出当前时间的小时和分钟
// 格式化输出结果"09:22"
//案例2
Date d = new Date(now)
s = String.format("%tD",d) //输出当前时间的month/day/year
// 格式化输出结果"11/05/15"
public class test1 { //新建类public static void main(String[] args) { //主方法
String str = String.format("%d",400/2) //将结果以十进制显示
String str2 = String.format("%b",3 >5) //将结果以布尔形式显示
String str3 = String.format("%x",200) //将结果以10进制格式显示
System.out.println("400的一半是:"+str) //输出格式化字符串
System.out.println("3>5正确吗:"+str2)
System.out.println("200的16进制数是:"+str3)
}
}
为什么会报错:
类型 String 中的方法 format(String, Object[])对于参数(String, int)不适用
类型 String 中的方法 format(String, Object[])对于参数(String, boolean)不适用
类型 String 中的方法 format(String, Object[])对于参数(String, int)不适用
这样的测试方法是不正确的。getBytes(charset)是解码,new String(byte[], charset)是编码。new String(str.getBytes(charset),charset)是解码再编码,无论charset是什么编码格式,返回的字符串内容原始str是一致,因此equals方法都是返回true,达不到测试字符串编码格式的目的。个人观点:正确的测试姿势应该是这样的:
String charset ="xxx" //假定编码格式String str = "中文";
boolean flag = str.equals(new String(str.getBytes(),charset))
flag为true则表明str的编码格式是假定的编码格式。其中说明str.getBytes()该方法就是按其自身编码格式去解码。其自身编码格式跟你的操作系统编码格式或你使用的IDE设置的文件的Text file encoding有关。