1. 字符串不變:字符串的值在建立後不能被更改。數組
String s1 = "abc"; s1 += "d"; System.out.println(s1); // "abcd" // 內存中有"abc","abcd"兩個對象,s1從指向"abc",改變指向,指向了"abcd"。
String s1 = "abc"; String s2 = "abc"; // 內存中只有一個"abc"對象被建立,同時被s1和s2共享。 System.out.println(s1==s2);//true
// 經過字符數組構造
char chars[] = {'a', 'b', 'c'};
String str2 = new String(chars);//abc
//經過字節數組構造 byte bytes[] = { 97, 98, 99 }; String str3 = new String(bytes);//abc
4.兩個字符串經過equals比較編碼
// 建立字符串對象 String s1 = "hello"; String s2 = "hello"; String s3 = "HELLO"; // boolean equals(Object obj):比較字符串的內容是否相同 System.out.println(s1.equals(s2)); // true System.out.println(s1.equals(s3)); // false System.out.println("‐‐‐‐‐‐‐‐‐‐‐"); //boolean equalsIgnoreCase(String str):比較字符串的內容是否相同,忽略大小寫 System.out.println(s1.equalsIgnoreCase(s2)); // true System.out.println(s1.equalsIgnoreCase(s3)); // true System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
public static void main(String[] args) { //建立字符串對象 String s = "helloworld"; // int length():獲取字符串的長度,其實也就是字符個數 System.out.println(s.length()); System.out.println("‐‐‐‐‐‐‐‐"); // String concat (String str):將將指定的字符串鏈接到該字符串的末尾. String s2 = s.concat("**hello itheima"); System.out.println(s2);// helloworld**hello itheima // char charAt(int index):獲取指定索引處的字符 System.out.println(s.charAt(0)); System.out.println(s.charAt(1)); System.out.println("‐‐‐‐‐‐‐‐"); // int indexOf(String str):獲取str在字符串對象中第一次出現的索引,沒有返回‐1 System.out.println(s.indexOf("l")); //2 System.out.println("owo="+s.indexOf("owo")); //owo=4 索引下標是重0開始 System.out.println(s.indexOf("ak")); System.out.println("‐‐‐‐‐‐‐‐"); // String substring(int start):從start開始截取字符串到字符串結尾 System.out.println(s.substring(0)); //helloworld System.out.println(s.substring(5)); //world 不包含5 索引下標是重1開始 不是從0開始 System.out.println("‐‐‐‐‐‐‐‐"); // String substring(int start,int end):從start到end截取字符串。含start,不含end。 System.out.println(s.substring(0, s.length())); //helloworld System.out.println(s.substring(3,8)); //lowor }
public static void main(String[] args) { //建立字符串對象 String s = "abcde"; // char[] toCharArray():把字符串轉換爲字符數組 char[] chs = s.toCharArray(); for(int x = 0; x < chs.length; x++) { System.out.println(chs[x]); }System.out.println("‐‐‐‐‐‐‐‐‐‐‐"); // byte[] getBytes ():把字符串轉換爲字節數組 byte[] bytes = s.getBytes(); for(int x = 0; x < bytes.length; x++) { System.out.println(bytes[x]); } System.out.println("‐‐‐‐‐‐‐‐‐‐‐"); // 替換字母it爲大寫IT String str = "itcast itheima"; String replace = str.replace("it", "IT"); System.out.println(replace); // ITcast ITheima System.out.println("‐‐‐‐‐‐‐‐‐‐‐"); }
public static void main(String[] args) { //建立字符串對象 String s = "aa|bb|cc"; String[] strArray = s.split("|"); // ["aa","bb","cc"] for(int x = 0; x < strArray.length; x++) { System.out.println(strArray[x]); // aa bb cc } }