java基礎回顧之String的構造方法

package com.bjpowernode.demo01;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

//String構造方法, 
public class Test01 {

	public static void main(String[] args) throws UnsupportedEncodingException {
		//1) 直接賦值字符串字面量
		String s1 = "hello";
		//2) 無參構造 
		String s2 = new String();		//長度爲0的字符串, 相當於"",空串
		//new運算符在堆區中創建一個對象 , 把該對象的引用(地址)賦值給s2變量
		System.out.println( s2.length() );
		
		//3)根據字節數組創建String對象
		byte[]bytes = {65,66,67,97,98,99,100};
		//把bytes字節數組中的內容, 根據當前默認的編碼格式(utf-8)轉換爲字符串
		String s3 = new String(bytes);
		System.out.println( s3 ); 		//ABCabcd
		//根據字節數組中的部分字節創建String對象, 把byte字節數組中從2開始的4個字節轉換爲字符串
		s3 = new String(bytes , 2 , 4);
		System.out.println( s3 );		//Cabc
		//把字節 數組中的字節轉換爲字符串時,可以指定編碼格式
		bytes = "hello,動力節點".getBytes(); 	//字符串的getBytes()可以把字符串轉換爲默認編碼下的字節數組
		System.out.println( Arrays.toString(bytes));
		//[104, 101, 108, 108, 111, 44, -27, -118, -88, -27, -118, -101, -24, -118, -126, -25, -126, -71]
		//utf-8編碼中, 一個英文字符佔1字節, 一個漢字佔3個字節
		s3 = new String(bytes, "UTF-8"); //使用utf-8編碼把字節數組轉換爲字符串
		System.out.println( s3 );
		s3 = new String(bytes, "GBK"); //使用GBK編碼把字節數組轉換爲字符串
		System.out.println( s3 );	//hello,鍔ㄥ姏鑺傜偣
		//在GBK編碼中,一個英文字符佔1字節,一個漢字佔2個字節
		
		//4) 根據字符數組創建字符串對象
		char[]contents = {'A','*','漢','妃','菲','6'};
		String s4 = new String(contents);
		System.out.println( s4 ); 	//A*漢妃菲6
		s4 = new String(contents, 2, 3);	//從2開始的3個字符轉換爲字符串
		System.out.println( s4 );
		
		//5) 根據已有的String對象創建新的字符串
		String s5 = new String(s4);
		System.out.println( s5 );
		System.out.println( s4 == s5 ); 		//false
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章