Java-String類的使用
目錄
Java-String類的使用 目錄 String類的使用的使用瞭解 1 String類概述 2 構造方法 String的使用程式碼範例 String的特點一旦被賦值就不能改變
1 String類的使用的使用(瞭解) 1.1 String類概述
字串是由多個字元組成的一串資料(字元序列)字串可以看成是字元數組
1.2 構造方法 public String():空構造 public String(byte[] bytes):把位元組數組轉成字串 public String(byte[] bytes,int index,int length):把位元組數組的一部分轉成字串 public String(char[] value):把字元數組轉成字串 public String(char[] value,int index,int count):把字元數組的一部分轉成字串 public String(String original):把字串常量值轉成字串 位元組數組 字元數組 字串
2 String的使用程式碼範例
public class StringDemo { public static void main(String[] args) { // public String():空構造 String s1 = new String(); System.out.println("s1:" + s1); System.out.println("s1.length():" + s1.length()); System.out.println("--------------------------"); // public String(byte[] bytes):把位元組數組轉成字串 byte[] bys = { 97, 98, 99, 100, 101 }; String s2 = new String(bys); System.out.println("s2:" + s2); System.out.println("s2.length():" + s2.length()); System.out.println("--------------------------"); // public String(byte[] bytes,int index,int length):把位元組數組的一部分轉成字串 // 我想得到字串"bcd" String s3 = new String(bys, 1, 3); System.out.println("s3:" + s3); System.out.println("s3.length():" + s3.length()); System.out.println("--------------------------"); // public String(char[] value):把字元數組轉成字串 char[] chs = { 'a', 'b', 'c', 'd', 'e', '愛', '林', '親' }; String s4 = new String(chs); System.out.println("s4:" + s4); System.out.println("s4.length():" + s4.length()); System.out.println("--------------------------"); // public String(char[] value,int index,int count):把字元數組的一部分轉成字串 String s5 = new String(chs, 2, 4); System.out.println("s5:" + s5); System.out.println("s5.length():" + s5.length()); System.out.println("--------------------------"); //public String(String original):把字串常量值轉成字串 String s6 = new String("abcde"); System.out.println("s6:" + s6); System.out.println("s6.length():" + s6.length()); System.out.println("--------------------------"); //字串字面值"abc"也可以看成是一個字串對象。 String s7 = "abcde"; System.out.println("s7:"+s7); System.out.println("s7.length():"+s7.length()); }}輸出:s1:s1.length():0--------------------------s2:abcdes2.length():5--------------------------s3:bcds3.length():3--------------------------s4:abcde愛林親s4.length():8--------------------------s5:cde愛s5.length():4--------------------------s6:abcdes6.length():5--------------------------s7:abcdes7.length():5
3 String的特點一旦被賦值就不能改變
/* * 字串的特點:一旦被賦值,就不能改變。 */public class StringDemo { public static void main(String[] args) { String s = "hello"; s += "world"; System.out.println("s:" + s); // helloworld }}