String是不變類,用String修改字符串會新建一個String對象,如果頻繁的修改,將會產生很多的String對象,開銷很大.因此java提供了一個StringBuffer類,這個類在修改字符串方面的效率比String高了很多。
在java中有3個類來負責字符的操作。
public class UsingStringBuffer { /** * 查找匹配字符串 */ public static void testFindStr() { StringBuffer sb = new StringBuffer(); sb.append("This is a StringBuffer"); // 返回子字符串在字符串中最先出現的位置,如果不存在,返回負數 System.out.println("sb.indexOf(/"is/")=" + sb.indexOf("is")); // 給indexOf方法設置參數,指定匹配的起始位置 System.out.println("sb.indexOf(/"is/")=" + sb.indexOf("is", 3)); // 返回子字符串在字符串中最后出現的位置,如果不存在,返回負數 System.out.println("sb.lastIndexOf(/"is/") = " + sb.lastIndexOf("is")); // 給lastIndexOf方法設置參數,指定匹配的結束位置 System.out.println("sb.lastIndexOf(/"is/", 1) = " + sb.lastIndexOf("is", 1)); } /** * 截取字符串 */ public static void testSubStr() { StringBuffer sb = new StringBuffer(); sb.append("This is a StringBuffer"); // 默認的終止位置為字符串的末尾 System.out.print("sb.substring(4)=" + sb.substring(4)); // substring方法截取字符串,可以指定截取的起始位置和終止位置 System.out.print("sb.substring(4,9)=" + sb.substring(4, 9)); } /** * 獲取字符串中某個位置的字符 */ public static void testCharAtStr() { StringBuffer sb = new StringBuffer("This is a StringBuffer"); System.out.println(sb.charAt(sb.length() - 1)); } /** * 添加各種類型的數據到字符串的尾部 */ public static void testAppend() { StringBuffer sb = new StringBuffer("This is a StringBuffer!"); sb.append(1.23f); System.out.println(sb.toString()); } /** * 刪除字符串中的數據 */ public static void testDelete() { StringBuffer sb = new StringBuffer("This is a StringBuffer!"); sb.delete(0, 5); sb.deleteCharAt(sb.length() - 1); System.out.println(sb.toString()); } /** * 向字符串中插入各種類型的數據 */ public static void testInsert() { StringBuffer sb = new StringBuffer("This is a StringBuffer!"); // 能夠在指定位置插入字符、字符數組、字符串以及各種數字和布爾值 sb.insert(2, 'W'); sb.insert(3, new char[] { 'A', 'B', 'C' }); sb.insert(8, "abc"); sb.insert(2, 3); sb.insert(3, 2.3f); sb.insert(6, 3.75d); sb.insert(5, 9843L); sb.insert(2, true); System.out.println("testInsert: " + sb.toString()); } /** * 替換字符串中的某些字符 */ public static void testReplace() { StringBuffer sb = new StringBuffer("This is a StringBuffer!"); // 將字符串中某段字符替換成另一個字符串 sb.replace(10, sb.length(), "Integer"); System.out.println("testReplace: " + sb.toString()); } /** * 將字符串倒序 */ public static void reverseStr() { StringBuffer sb = new StringBuffer("This is a StringBuffer!"); System.out.println(sb.reverse()); // reverse方法將字符串倒序 } }
小結:
StringBuffer不是不變類,在修改字符串內容時,不會創建新的對象,因此,它比String類更適合修改字符串;
StringBuffer類沒有提供同String一樣的toCharArray方法;
StringBuffer類的replace方法同String類的replace方法不同,它的replace方法有三個參數,第一個參數指定被替換子串的起始位置,第二個參數指定被替換子串的終止位置,第三個參數指定新子串。
以上就是本文的全部內容,希望對大家的學習有所幫助。
新聞熱點
疑難解答