JAVA筆記-API-String類常用方法

String類

字符串:多個字符組成的一串數據,像是字符數組
字符串是常量,不能更改,字符串緩衝區可以更改
字符串值不能改變,但引用可以改變。

構造方法(常用)
A:public String()
B:public String(byte[] bytes)//數組轉字符串,注意保存的是對應的ascii碼
C:public String(byte[] bytes,int index,int length)//從第index開始,length個
D:public String(char[] value)//字符數組轉字符串
E:public String(char[] value,int index,int count)
F:public String(String original)//String s=new String("a");意義不大,不如G方法
下面的這一個雖然不是構造方法,但是結果也是一個字符串對象
G:String s = "hello";

面試題
String s=new String("hello");String s="hello"; 兩者區別
前者創建兩個對象(一個在堆內存中創建String類對象,一個在方法區創建hello對象)
後者只創建1個對象。兩者地址不同,內容相同,前者爲堆中類對象地址,後者爲方法區
字符串常量池中hello地址。
(字符串變量相加,先開空間再拼接)
String s1="helloworld";
String s2="hello";
String s3="world";
syso(s3==s1+s2);//false
syso(s3=="hello"+"world");//true

成員方法:
判斷功能:
    boolean equals(Object obj);//判斷字符串內容是否相同
    boolean equalsIgnoreCase(String str);//不區分大小寫判斷內容
    boolean contains(String str);//判斷此字符串中是否包含str字符串內容
    boolean startsWith(String str);//判斷此字符串是否以str字符串開頭
    boolean endsWith(String str);//判斷此字符串是否以str字符串結尾
    boolean isEmpty();//判斷此字符串是否爲空
        字符串爲空(String s=null;),調用isEmpty()方法會報錯,因爲根本沒有對象無法調方法
        字符串內容爲空(String s="";)

獲取功能:(public)
    int length()//返回字符串長度
    int indexOf(int ch)//返回指定字符在此字符串中第一次出現的索引
     'a'=97;
    int indexOf(String str)//返回指定字符串在此字符串中第一次出現的索引
         int indexOf(int ch,int fromIndex)//返回指定字符在此字符串中指定位置後第一次出現的索引
    int indexOf(String str,int fromIndex)//返回指定字符串在此字符串中指定位置後第一次出現的索引
            char charAt(int index)//獲取指定索引位置的字符
         String substring(int start)//從指定位置到末尾截取字符串(包含start)
    String substring(int start,int end)//從指定位置到指定結尾截取字符串,前閉後開


轉換功能:
    byte[] getBytes() //把字符串轉換成字節數組
    char[] toCharArray() //把字符串轉換成字符數組
    static String valueOf(char[] chs) //把字符數組轉換成字符串
    static String valueOf(int i) //把數據轉換成字符串
    String toLowerCase() //把字符串轉換小寫
    String toUpperCase() //轉換大寫
     String concat(String str) //字符串拼接
 
其他功能:
    替換:
String replace(char old,char new)
String replace(String old,String new)
    去除字符串兩端空格:
String trim()
    按字典順序比較兩個字符串
int compareTo(String str)
int compareToIgnoreCase(String str)

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