连接字符串的四种方式:
String str1="111";
String str2="222";
// concat()
System.out.println("第一种方法:"+str1.concat(str2));
// +
System.out.println("第二种方法:"+str1+str2);
//String.format()
System.out.println("第三种方法:"+String.format("%s%s",str1,str2));
// append()
StringBuffer s1 = new StringBuffer(str1);
s1.append(str2);
System.out.println("第四种方法:"+s1);
几种方式的消耗时间()
package com.haier.openplatform.fxst.util;
import java.util.Date;
public class test2 {
/**
* 测试 == 拼接字符串的几种方法的效率
* @time:2018年6月13日
* @TODO
* void
* @param args
*/
public static void main(String[] args) {
test2.a();
test2.b();
test2.c();
test2.d();
}
//@1定义一个方法
public static void a(){
//开始时间
long StartTime = new Date().getTime();//从1970.1.1开始的毫秒数
String string = new String();
//定义一个循环
for (int i = 0; i < 5000; i++) {
string = string + i;
}
//结束时间
long EndTime = new Date().getTime();
System.out.println(StartTime);
System.out.println(EndTime);
System.out.println("时间"+ (EndTime-StartTime));
}
//@2
public static void b(){
//开始时间
long StartTime = new Date().getTime();//从1970.1.1开始的毫秒数
String string = new String();
//定义一个循环
for (int i = 0; i < 5000; i++) {
string += i;
}
//结束时间
long EndTime = new Date().getTime();
System.out.println(StartTime);
System.out.println(EndTime);
System.out.println("时间"+ (EndTime-StartTime));
}
//@3
public static void c(){
//开始时间
long StartTime = new Date().getTime();//从1970.1.1开始的毫秒数
String string = new String();
//定义一个循环
for (int i = 0; i < 5000; i++) {
string = string.concat(string.valueOf(i));
}
//结束时间
long EndTime = new Date().getTime();
System.out.println(StartTime);
System.out.println(EndTime);
System.out.println("时间"+ (EndTime-StartTime));
}
//@4
public static void d(){
//开始时间
long StartTime = new Date().getTime();//从1970.1.1开始的毫秒数
String string = new String();
StringBuffer stringBuffer = new StringBuffer();
//定义一个循环
for (int i = 0; i < 5000; i++) {
stringBuffer = stringBuffer.append(i);
}
string = string + stringBuffer;
//结束时间
long EndTime = new Date().getTime();
System.out.println(StartTime);
System.out.println(EndTime);
System.out.println("时间"+ (EndTime-StartTime));
}
}