String 類的常用方法

String類的常用方法

    

        String tom=new String("we are students");
        String body=new String("you are students");
        String jerry=new String("we are students");


/**int length()*/
        System.out.println(tom.length());/*獲取tom字符串的長度*/



/**boolean equals(String s)*/
        System.out.println(tom.equals(body));   //比較當前字符串對象的實體是否與參數body指定的字符串的實體相同。正確返回true 否則返回false



/**boolean startsWith(String s)*/
        System.out.println(tom.startsWith("we"));   //startsWith比較當前字符串對象的前綴是否是參數"we"指定的字符串.  正確返回true 否則返回false



/**boolean regionMatches(int firstStart,String other,int otherStart,int length)*/
        System.out.println(tom.regionMatches(5,"e s",0,3));     /*從當前字符串tom位置“5”處,取長度爲“3”的一個子串,並將這個子串和參數“e s”從“0”位置開始取長度爲“3”進行比較,正確返回true 否則返回false*/



/**int compareTo(String s)*/
        if(tom.compareTo(jerry)>0){     /*tom字符串按字典序與參數(jerry)字符串比較大小,相同返回0,大於返回正值,小於返回負值。*/
            System.out.println("tom大於jerry");
        }else if(tom.compareTo(jerry)<0){
            System.out.println("tom小於jerry");
        }else if(tom.compareTo(jerry)==0){
            System.out.println("tom等於jerry");
        }



/**boolean contains(String s)*/
        if(tom.contains("we")){     /*tom字符串中是否含有“we”字符串,含有返回true,否則返回false*/    
            System.out.println("tom字符串中含有“we”");
        }



/**int indexOf(String s)*/
        System.out.println(tom.indexOf("e"));/*從tom字符串的頭開始檢索字符“e”,並返回首次發現“e”的位置*/


        System.out.println(tom.indexOf("e",3));/*從tom字符串的“3”位置開始檢索字符“e”,並返回首次發現“e”的位置*/

        


/**int lastIndexOf(String s)*/
        System.out.println(tom.lastIndexOf("e"));/*從tom字符串的尾開始檢索字符“e”,並返回首次發現“e”的位置*/



/**String substring(int startpoint)*/
        System.out.println(tom.substring(3));   /*獲得從tom字符串的"3"位置開始截取到最後的字符串*/


        System.out.println(tom.substring(3,5));     /*獲得從tom字符串的"3"位置開始截取到"5"位置(不包括5)的字符串*/  
       


/**String trim()*/
        System.out.println(tom.trim());     /*獲取tom字符串去掉前後空格後所剩字符串*/

        


/**void getChars(int start,int end,char c[],int offset)*/
        char a[]=new char[50];
        tom.getChars(0,5,a,3);  /*將tom字符串從“0”位置開始到“5-1”位置截取子串賦給a數組,a數組從“3”位置開始存放這些字符*/
        System.out.println(a);



/**String concat();*/     

        System.out.println(tom.concat(tom));

        /**在tom後面追加tom字符串*/



/**String replace();*/  

        System.out.println(tom.replace("e","a"));

        /**將tom中的e替換成a*/


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