1. 程式人生 > >java學習筆記五--String類與String例子

java學習筆記五--String類與String例子

請解釋字串比較之中“==”和equals()的區別?
         ==:比較的是兩個字串記憶體地址的數值是否相等,屬於數值比較;
        equals():比較的是兩個字串的內容,屬於內容比較。
        以後進行字串相等判斷的時候都使用equals()

字串常量就是一個匿名物件,匿名物件永遠不可能為null

在String類進行設計的時候採用了一種稱為共享設計模式的概念,在每一個執行的JVM底層存在一個字串的物件池(Object Pool),如果使用者採用了直接賦值的方式,會將字串的內容放入到池之中,以供其他繼續使用直接賦值方式的String物件使用,如果新宣告的字串內容不在池之中,則會開闢一個新的,繼續放到池,以供下次使用。
   
public class StringDemo {




	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String a="hello";
		String b="hello";
		String c="hello";
		String d=new String("hello");
		System.out.println(a==b);
		System.out.println(a==c);
		System.out.println(b==c);
		System.out.println(d==a);
	}




}
 使用構造方法的方式開闢的字串物件,實際上會開闢兩塊空間,其中有一塊空間將稱為垃圾。
public class StringDemo {
         public static void main(String args[]) {
                   String str1 = new String("Hello") ;
                   String str2 = "Hello" ;  // 入池
                   String str3 = "Hello" ;  // 使用池物件
                   System.out.println(str1 == str2) ;    // false
                   System.out.println(str1 == str3) ;    // false
                   System.out.println(str2 == str3) ;    // true
         }
}
通過上面的程式可以發現,使用構造方法例項化的String物件,不會入池,所以,只能自己使用。可是在String類之中為了方便操作提供了一種稱為手工入池的方法:public String intern()。
public class StringDemo {
         public static void main(String args[]) {
                   String str1 = new String("Hello").intern() ;
                   String str2 = "Hello" ;  // 入池
                   String str3 = "Hello" ;  // 使用池物件
                   System.out.println(str1 == str2) ;    // true
                   System.out.println(str1 == str3) ;    // true
                   System.out.println(str2 == str3) ;    // true
         }
}
面試題:請解釋String類的兩種物件例項化方式的區別?
         · 直接賦值:只開闢一塊堆記憶體空間,字串的內容可以自動入池,以供下次使用;
         · 構造方法:開闢兩塊堆記憶體空間,有一塊將成為垃圾,並且不能自動入池,使用intern()手工入池。
         在日後的所有開發之中,String物件的例項化永遠都採用直接賦值的方式完成。
 
字串內容的更改,實際上改變的是字串物件的引用過程,並且會伴隨有大量的垃圾出現,那麼對於以下的程式碼實際之中應該避免:
public class StringDemo {
         public static void main(String args[]) {
                   String str = "" ;
                   for (int x = 0 ; x < 1000 ; x ++) {
                            str += x ;
                   }
                   System.out.println(str) ;
         }
}
但是這種程式碼需要“斷開-連線”String物件1000次,會產生大量垃圾,所以不能夠去使用。

 
public String(char[] value) 構造 將全部的字元陣列內容變為字串
public String(char[] value, int offset, int count) 構造 將部分字元陣列變為字串,offset表示開始點,count表示要操作的長度
public char charAt(int index) 普通 取得指定索引位置上的字元public char[] toCharArray() 普通 將字串轉換為字元陣列


字串和字元陣列轉換,完成一個小寫字串變為大寫字串的操作,小寫字母和大寫字母差了32
public class StringDemo {
         public static void main(String args[]) {
                   String str = "helloworld" ;
                   char data [] = str.toCharArray() ;     // 字串變為字元陣列
                   for (int x = 0 ; x < data.length ; x ++) {
                            System.out.print(data[x] + "、") ;
                            data [x] -= 32 ;    // 變大寫
                   }
                   System.out.println() ;
                   System.out.println("全部字元陣列變為字串:" + new String(data)) ;
                   System.out.println("部分字元陣列變為字串:" + new String(data,0,5)) ;
         }
}

現在要求判斷一個字串是否由數字所組成
public class StringDemo {
         public static void main(String args[]) {
                   char c = '8' ;
                   System.out.println(c >= '0' && c <= '9') ;
                   System.out.println((int) c) ;
         }
}

將一個字串首先變為字元陣列,而後依次判斷字元陣列之中的每一個字元是否是數字,如果全是,則返回true,否則返回false
public class StringDemo {
         public static void main(String args[]) {
                   String str = " 1a 23" ;
                   System.out.println(isNumber(str)) ;
         }
         public static boolean isNumber(String temp) {
                   char data [] = temp.toCharArray() ;    // 變為字元陣列
                   for (int x = 0 ; x < data.length ; x ++) {
                            if (data[x] < '0' || data[x] > '9') {
                                     return false ;      // 不是數字
                            }
                   }
                   return true ;
         }
}


public String(byte[] bytes) 構造 將全部的位元組陣列變為字串
public String(byte[] bytes, int offset, int length) 構造 將部分的位元組陣列變為字串
public byte[] getBytes() 普通 將字串變為位元組陣列
public byte[] getBytes(String charsetName) throws UnsupportedEncodingException 普通 字串轉碼操作
 
一般情況下,在程式之中如果要想操作位元組陣列只有兩種情況:
                   · 情況一:需要進行編碼的轉換時;
                   · 情況二:資料要進行傳輸的時候。
   

public boolean equals(String anObject) 普通 區分大小寫的相等判斷
public boolean equalsIgnoreCase(String anotherString) 普通 不區分大小寫比較是否相等
public int compareTo(String anotherString) 普通 比較兩個字串的大小
public boolean contains(String s) 普通 查詢指定的子字串是否存在,JDK 1.5之後有
public int indexOf(String str) 普通 從頭查詢指定字串的位置,找不到返回-1
public int indexOf(String str, int fromIndex) 普通 由指定位置向後查詢字串的位置,找不到返回-1
public int lastIndexOf(String str) 普通 由後向前查詢字串的位置,找不到返回-1
public int lastIndexOf(String str, int fromIndex) 普通 從指定位置由後向前查詢
public boolean startsWith(String prefix) 普通 判斷是否以指定的字串開頭
public boolean startsWith(String prefix, int toffset) 普通 從指定位置判斷是否以指定字串開頭,JDK 1.7
public boolean endsWith(String suffix) 普通 判斷是否以指定的字串結尾
public String replaceAll(String regex, String replacement) 普通 全部替換
public String replaceFirst(String regex, String replacement) 普通 替換首個
public String substring(int beginIndex) 普通 從指定位置擷取到結尾
public String substring(int beginIndex, int endIndex) 普通 擷取指定範圍的內容
public String[] split(String regex) 普通 按照指定的字串全拆分
public String[] split(String regex, int limit) 普通 拆分為指定的長度

public class StringDemo {
         public static void main(String args[]) {
                   String str = "192.168.1.1" ;
                   String result []= str.split("\\.") ;
                   for (int x = 0 ; x < result.length ; x ++) {
                            System.out.println(result[x]) ;
                   }
         }
}

public boolean isEmpty() 普通 判斷是否為空字串("")
public int length() 普通 取得字串長度
public String trim() 普通 去掉左右空格
public String toLowerCase() 普通 將全部字串轉小寫
public String toUpperCase() 普通 將全部字串轉大寫
public String intern() 普通 入池
public String concat(String str) 普通 字串連線

可以讓首字母大寫,可是這個方法其實很重要,但是String類沒有提供。下面簡單實現一下,給一個基本的原理。
public class StringDemo {
         public static void main(String args[]) {
                   String str = "hello" ;
                   System.out.println(initcap(str)) ;
         }
         public static String initcap(String s) {
                   return s.substring(0,1).toUpperCase().concat(s.substring(1)) ;
         }
}