String:
String在java中表示定长字符串,一旦对String初始化,则无法修改内容,除非重新赋值(创建新对象),所以String在进行大量字符串拼接时会频繁创建新对象,从而影响程序的运行效率;
StringBuffer:
StringBuffer是一个长度可变的字符序列,可以动态在原来字符串缓冲区的基础上追加(append)或者插入(insert)新的字符序列,而不会修改对象的内存地址,所以使用StringBuffer在完成字符串拼接时效率较高,另外StringBuffer是线程安全的实现,所以在线程并发操作时效率会有所影响
public class StringAppendDemo {
/*
* 测试使用String进行字符串拼接的效率
*/
public void test1(int count){
String s = "";
for(int i = 0;i < count;i++){
s += "hello";
}
}
/*
*
* 测试使用StringBuffer进行字符串拼接的效率
*/
public void test2(int count){
StringBuffer sb = new StringBuffer();
for (int i = 0; i < count; i++) {
sb = sb.append("hello");
}
}
public static void main(String[] args) {
StringAppendDemo sad = new StringAppendDemo();
//获取当前系统时间
long start = System.currentTimeMillis();
// sad.test1(10000);
sad.test2(10000);
//获取当前系统时间
long end = System.currentTimeMillis();
System.out.println("方法所耗时间:"+(end - start)+"ms");
}
}
由此可见在字符串拼接上StringBuffer比String效率更高
String类常用构造器
-
String()
-
String(String content)
-
String(char[] c)
-
String(char[] c,int offset,int len)
-
String(byte[] b)
-
String(byte[] b,offset,int len)
String类常用方法
-
char charAt(int index) :获取指定索引处的字符值
-
int compareTo(String str):按字典比较两个字符串的顺序,返回两个字符串间隔的字符数
-
String concat(String str):字符串连接,返回新的字符串
-
boolean contains(String str):判断当前字符串是否包含指定的子串
-
boolean endsWith(String suffix):判断字符串是否以指定的后缀结束
-
boolean equals(String str):判断两个字符串字面值是否一致
-
boolean equalsIgnoreCase(String str):忽略大小写比较两个字符串是否相等
-
byte[] getBytes():将字符串转换为字节数组
-
int indexOf(String str):获取指定字符串在当前字符串中第一次出现的位置
-
boolean isEmpty():判断字符串对象是否为空(非null),当且仅当length()为0时输出true
-
int length():获取字符串中字符的个数
-
boolean matches(String regex):判断字符串是否匹配指定的正则表达式
-
String replace(CharSequence oldValue,CharSequence newValue):字符串替换,后者替换前者
-
String[] split(String regex)根据指定的正则表达式将字符串截取并生成新的字符串数组
-
String substring(int beginIndex,int endIndex):字符串截取
-
String toUpperCase(String str)/String toLowerCase(String str):大小写转换
-
String trim():去除字符串前置与后置空格
-
static String join(String delimiter,CharSequence... c):使用指定分隔符对将多个字符序列拼接并返回