Java 字符串 之 字符,字節,字符串的轉換


http://www.verejava.com/?id=16993019638884

/**
題目: String 類的相關操作
	1. 字符與字符串轉換操作
	2. 字節與字符串轉換操作
	3. 判斷操作
	4. 替換操作
	5. 字符串的截取
	6. 字符串的拆分
	7. 字符串的查找
	8. 字符串其他操作
*/
public class TestString1
{
	public static void main(String[] args)
	{
		/*
		1.字符與字符串的轉換
			1. char[] toCharArray()   字符串 轉換成 字符數組
			2. char charAt(int index) 獲取索引位置的字符
			3. int length()			  獲得字符總個數的方法
			4. String new String(char[] value) 將字符數組轉換成字符串
			5. String new String(char[] value,int offset,int count) 將字符數組從		offset索引開始的count個字符轉換成字符串

		*/
			String str="Hello Welcome";
			//說明: 將字符串轉換成字符數組輸出
			char[] chars=str.toCharArray();
			for(int i=0;i<chars.length;i++)
			{
				System.out.println(chars[i]);
			}

			System.out.println("\n-------------------");
			//說明: 直接通過索引獲取字符輸出
			for(int i=0;i<str.length();i++)
			{
				System.out.println(str.charAt(i));
			}

			System.out.println("\n-------------------");
			//說明: 將字符數組轉換成字符串
			char[] chars2={'G','o','o','d',' ','M','o','r','n','i','n','g'};
			System.out.println(new String(chars2));
			System.out.println(new String(chars2,0,4));

		System.out.println("\n----------------------");
		/*
		2. 字節與字符串的轉換
			1. byte[] getBytes() 將字符串轉換成字節數組
			2. String new String(byte[] bytes) 將字節數組轉換成字符串
			3. String new String(byte[] bytes,int offset,int count) 將字節數組從	
				offset 索引開始的 count 個字節轉換成字符串

			作用: 因為java中數據是以字節byte為單位傳輸的,所以在以后輸入輸出流I/O當中用到
		*/
			//說明: 將字符串轉換成字節數組打印輸出
			String str3="How are you";
			byte[] bytes=str3.getBytes();
			for(int i=0;i<bytes.length;i++)
			{
				System.out.println(bytes[i]+"-"+(char)bytes[i]);
			}

			//說明: 將字節數組轉換成字符串輸出
			byte[] bytes2={65,66,67,68};
			System.out.println(new String(bytes2));
			System.out.println(new String(bytes2,0,2));

		

	}
}

http://www.verejava.com/?id=16993019638884


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM