Java學習筆記1——String類

一、String類
1、概念:字符串,是多個字符組成的一串數據。
位於java.lang包。
String類是一個被final修飾的類,表示不可被繼承和修改。字符串的底層存儲結構是char數組。

public final class String{...}

2、部分的構造函數
(1)空構造函數:String()
初始化一個新的空字符串對象

String str = new String();

(2)以String對象爲參數:String(String string)

創建一個String類對象s,並將一個字符串str賦予新的String對象s

String s = new String("str");

(3)以字符數組爲參數構造String:String(char value[])

創建一個String對象,將chs傳入賦予s

char[] chs = {'a','b','c'};
String s = new String(chs);

(4)傳入字符數組的子數組:String(char value[], int offset, int count)
將字符數組value(chs)從第offset位開始,傳入長度爲count的子數組構造成字符串s。

char[] chs = {'a','b','c','d','e'};
String s = new String(chs,1,3);

(5)傳入整型int數組的子數組,構造對應字符的字符串:String(int[] codePoints, int offset, int count)
傳入的數組爲整型數組,將爲轉換爲ASCII對應的字符。

int[] chs = {65,66,67,68,97,97};
String s = new String(chs,1,3);

(6)傳入字節數組的子數組構建String對象:public String(byte bytes[], int offset, int length)
傳入一個字節數組,從第offset個位置開始,取長度爲length的子數組,構建一個新的字符串s。

byte[] chs = {1,2,3,4,5};
String s = new String(chs,1,3);

(7)傳入字節數組構建String對象:public String(byte bytes[])
傳入一個字符數組,構建一個新的字符串對象s。

byte[] chs = {1,2,3,4,5};
String s = new String(chs);

此構造方法是通過調用this(bytes, 0, bytes.length);即上述(6)的方法。

(8)傳入字符數組,以指定編碼構造字符串:public String(byte bytes[], int offset, int length, String charsetName)
指定編碼傳入字符數據構造字符串。

byte[] chs = {61,66,60,68,97,97};
String s = new String(chs,1,3,"GBK");

(9)傳入StringBuffer並將轉化爲String:public String(StringBuffer buffer)
傳入StringBuffer,調用toString()方法轉化爲字符串。

StringBuffer buffer = new StringBuffer("Hello World!");
String s = new String(buffer);

(10)傳入StringBuilder並轉化爲String:public String(StringBuilder builder)
傳入StringBuilder,調用toString()方法轉化爲字符串。與(9)同理。

StringBuilder builder = new StringBuilder("Hello World!");
String s = new String(builder);

3、常用方法
A:判斷方法
(1)判斷字符串的內容是否相同,區分大小寫:public boolean equals(Object obj)
(2)判斷字符串的內容是否相同,區分大小寫:public boolean equalsIgnoreCase(String str)
(3)判斷字符串對象是否包含指定的字符串:public boolean contains(String str)
(4)判斷字符串對象是否以指定的字符串開始:public boolean startsWith(String str)
(5)判斷字符串對象是否以指定的字符串結尾:public boolean endsWith(String str)
(6)判斷字符串對象或數據是否爲空:public boolean isEmpty()
(7)獲取指定位置的字符的ACSII碼:public int codePointAt(int index)
(8)獲取指定位置的前一個字符的ACSII碼:public int codePointBefore(int index)

例子:

public class StringDemo {  
    public static void main(String[] args) {  
        // 創建字符串對象  
        String str = "Hello World!";  

        // boolean equals(Object obj)
        // 判斷字符串內容是否相同,區分大小寫
        System.out.println(s.equals("Hello World!"));  
        System.out.println(s.equals("hello world!"));  
        System.out.println("--------------------");  

        // boolean equalsIgnoreCase(String str)
        // 判斷字符串內容是否相同,不區分大小寫
        System.out.println(s.equalsIgnoreCase("Hello World!"));
        System.out.println(s.equalsIgnoreCase("Hello World!")); 
        System.out.println("--------------------");  

        // boolean contains(String str)
        // 判斷字符串對象是否包含指定的字符串
        System.out.println(s.contains("llo"));  
        System.out.println(s.contains("orr"));  
        System.out.println("--------------------");  

        // boolean startsWith(String str)
        // 判斷字符串對象是否以指定的字符串開始  
        System.out.println(s.startsWith("Hel"));  
        System.out.println(s.startsWith("hello"));  
        System.out.println("--------------------");  

        // boolean endsWith(String str)
        // 判斷字符串對象是否以指定的字符串結束  
        System.out.println(s.endsWith("orld!"));  
        System.out.println(s.endsWith("world!"));  
        System.out.println("--------------------");  

        // boolean isEmpty()
        // 判斷字符串對象或數據是否爲空
        System.out.println(s.isEmpty());  
        String s2 = "";  
        System.out.println(s2.isEmpty());  
        // String s3 = null;  
        // NullPointerException 空指針異常  
        // System.out.println(s3.isEmpty());  
    }  
}  

B:獲取方法
(1)獲取字符串的長度:public int length()
(2)獲取指定字符在此字符串中第一次出現的位置:public int indexOf(int ch)
(3)獲取指定字符串在此字符串中第一次出現的位置:public int indexOf(String str)
(4)獲取在此字符串中第一次出現指定字符的位置,從指定的位置開始搜索:public int indexOf(int ch,int fromIndex)
(5)獲取在此字符串中第一次出現指定字符串的位置,從指定的位置開始搜索:public int indexOf(String str,int fromIndex)
(6)獲取在此字符串中最後出現的指定字符串的位置:public int lastIndexOf(String str)
(7)lastIndexOf的其他不同方法與indexOf類似
(8)獲取字符串中指定位置的字符:char charAt(int index)
(9)獲取從指定位置開始到最後的字符串:String substring(int start)
(10)獲取指定範圍的字符串:public String substring(int beginIndex, int endIndex)
(11)將字符串按照指定規則進行切割,獲得一個切割後的字符串數組:public String[] split(String regex)
(12)去除兩端空格:public String trim()

例子:

public class StringDemo {

    public static void main(String[] args) throws UnsupportedEncodingException {

        String s = "Hello World!";

        // int length()
        // 獲取字符串的長度
        System.out.println(s.length());
        System.out.println("--------------");

        // char charAt(int index)
        System.out.println(s.charAt(2));  
        System.out.println("--------------");

        // int indexOf(int ch)
        System.out.println(s.indexOf('o'));
        System.out.println("--------------");

        // int indexOf(int ch,int fromIndex)
        System.out.println(s.indexOf('o', 5));
        System.out.println("--------------");

        // int lastIndexOf(int ch)
        System.out.println(s.lastIndexOf('o'));
        System.out.println("--------------");

        // int lastIndexOf(int ch,int fromIndex)
        System.out.println(s.lastIndexOf('o', 5));
        System.out.println("--------------");

        // String substring(int start) 
        System.out.println(s.substring(4));  
        // String substring(int start,int end)
        System.out.println(s.substring(4, 8));  
        System.out.println("--------------");

        // String[] spilt(String regex)
        String strs = "hello|world|hey"
        System.out.println(s.spilt("|"));

    }
}

C:轉換功能
(1)把字符串轉換成字節數組:public byte[] getBytes()
(2)把字符串轉換成字符數組:public char[] toCharArray()
(3)把字符數組轉換成字符串:public static String copyValueOf(char[] chs)
(4)把字符數組轉換成字符串:public static String valueOf(char[] chs)
(5)把int(基本類型)轉換成字符串:public static String valueOf(int i)
(還有其他基本類型的轉換)
(6)把字符串變成小寫:String toLowerCase()
(7)把字符串變成大寫:String toUpperCase()
(8)拼接字符串:String concat(String str)

例子:

public class StringDemo {  
    public static void main(String[] args) {  
        // 創建字符串對象  
        String s = "Hello World!";  

        // byte[] getBytes()
        byte[] bys = s.getBytes();  
        for (int x = 0; x < bys.length; x++) {  
            System.out.println(bys[x]);  
        }  
        System.out.println("-----------------");  

        // char[] toCharArray()  
        char[] chs = s.toCharArray();  
        for (int x = 0; x < chs.length; x++) {  
            System.out.println(chs[x]);  
        }  
        System.out.println("-----------------");  

        // static String copyValueOf(char[] chs)
        char[] chs2 = { '大', '佬', 's', 'n', 'm' };  
        String s2 = String.copyValueOf(chs2);  
        System.out.println(s2);  
        System.out.println("-----------------");  

        // static String valueOf(char[] chs)  
        String s3 = String.valueOf(chs2);  
        System.out.println(s3);  
        System.out.println("-----------------");  

        // static String valueOf(int i)  
        int i = 666;  
        String s4 = String.valueOf(i);  
        System.out.println(s4);  
        System.out.println("-----------------");  

        // String toLowerCase()
        System.out.println(s.toLowerCase());  
        // String toUpperCase() 
        System.out.println(s.toUpperCase());  
        System.out.println("-----------------");  

        // String concat(String str) 
        String s5 = "hello";  
        String s6 = s5 + "world";  
        String s7 = s5.concat("world");  
        System.out.println(s6);  
        System.out.println(s7);  
    }  
}  

D:替換功能
(1)用新的字符去替換指定的舊字符:String replace(char oldChar,char newChar)
(2)用新的字符串去替換指定的舊字符串:String replace(String oldString,String newString)

例子:

public class StringDemo {  
    public static void main(String[] args) {  
        // 創建字符串對象  
        String s1 = "Hello";  
        String s2 = "Hello";
        //char與String的區別在於單引號與雙引號
        System.out.println(s1.replace('H', 's'));   
        System.out.println(s2.replace("H", "S"));   

    }  
}  

E:字典順序比較功能
(1)返回前後比較的兩個字符串的ACSII碼的差值:public int compareTo(String str)
如果兩個字符串首字母不同,則該方法返回首字母的ACSII碼的差值
(2)忽略大小寫,返回前後比較的兩個字符串的ACSII碼的差值:public int compareToIgnoreCase(String str)

例子:

public class StringDemo {  
    public static void main(String[] args) {  
        // 創建字符串對象  
        String s1 = "Hello";  
        String s2 = "hello";
        String s3 = "aello";
        String s4 = "Helle";

        System.out.println(s1.compareTo(s2));   //-32
        System.out.println(s1.compareTo(s3));   //-25
        System.out.println(s1.compareTo(s4));   //10
        System.out.println("----------------------");

        System.out.println(s1.compareToIgnoreCase(s2));     //0
        System.out.println(s1.compareToIgnoreCase(s3));     //7
        System.out.println(s1.compareToIgnoreCase(s4));     //10
    }  
}  

二、常見問題
1、字符串比較
這裏可以包括了其他類型的比較,此處僅用String。

String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
String s4 = new String(s1);
System.out.println(s1==s2);//true
System.out.println(s1==s3);//false
System.out.println(s1==s4);//false
System.out.println(s3==s4);//false
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//true

第一個:s1==s2。結果爲true,s1和s2引用的“hello”是常量,在常量池中,故是true。
第二個:s1==s3。結果爲false,s3是通過new創建的對象,存放在堆內存中,所以比較時不一樣。
第三個:s1==s4。結果爲false,同理。
第四個:s1.equals(s3)。結果爲true。equals是比較兩者內容是否相同。
第五個:s1.equals(s4)。結果爲true,同理。

2、String的內容是否能夠改變?
這個涉及到了final。final修飾後,指的是,引用變量不能變,引用變量所指向的對象中的內容還是可以改變的。
通常看到修改的String內容,只是String修改了內容指向,原本的內容並未改變。

3、String s = new String(“abc”)創建了多少個String對象?
兩個或一個,”abc”對應一個對象,這個對象放在字符串常量緩衝區,常量”abc”不管出現多少遍,都是緩衝區中的那一個。new String每寫一遍,就創建一個新的對象,它一句那個常量”abc”對象的內容來創建出一個新String對象。如果以前就用過’abc’,這句代表就不會創建”abc”自己了,直接從緩衝區拿。

4、String和StringBuilder和StringBuffer的區別
String、StringBuilder和StringBuffer,它們可以儲存和操作字符串,即包含多個字符的字符數據。
這個String類提供了數值不可改變的字符串。而這個StringBuilder和StringBuffer類提供的字符串進行修改。
String覆蓋了equals方法和hashCode方法,而StringBuffer沒有覆蓋equals方法和hashCode方法,所以,將StringBuffer對象存儲進Java集合類中時會出現問題。
StringBuilder和StringBuffer的區別是是否安全等等。
當需要頻繁修改字符串的時候,建議使用StringBuffer。
單線程操作時推薦使用StringBuilder,效率更高。
多線程時操作推薦使用StringBuffer,更加安全。

5、對亂序的字符串(字符串中的字符是亂序的)進行排序

public class StringDemo {  
    public static void main(String[] args) {  
        String s = "xzcnjeum";
        char[] chs = s.toCharArray();
        //排序方法不限
        for(int i = 0;i<chs.length;i++){
            for (int j = 0; j < chs.length - 1 - i; j++) {  
                if (chs[j] > chs[j + 1]) {  
                    char ch = chs[j];  
                    chs[j] = chs[j + 1];  
                    chs[j + 1] = ch;  
                }  
            }  
        }
        System.out.println(chs);
    }  
}  

當然還有很多沒有寫好,也是第一次寫學習筆記,如果有什麼問題歡迎指出。

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