1. 程式人生 > >常用的String類方法

常用的String類方法

方法包含在java.lang.String中。String型別一經建立就不可改變。可變的字串可用StringBuffer型別或者StringBuilder型別。
程式碼如下:

package Stringpackage;

public class StringFunction {
    public static void main(String[] args)
    {
        String a=new String("abcdefg");
        String b=new String("Abcdefg");
        String c=new String("a bc"
); String d=new String("abcabcabcabc"); //按字典順序比較兩個字串,返回int值,相等返回0,小於字串引數返回小於0的值,大於字串引數返回大於0的值; System.out.println("The result of a compare to b is "+a.compareTo(b)+"\n"+"The result of b compare to a is "+a.compareTo(c)); System.out.println("----------------------------------"
); //按字典順序比較兩個字串,忽略大小寫; System.out.println("a compare to b ignoring case : "+a.compareToIgnoreCase(b)); System.out.println("----------------------------------"); //將字串引數連線到字串的末尾; System.out.println("connect b to the end of a: "+a.concat(b)); System.out.println
("----------------------------------"); // 當且僅當此字串包含指定的 char 值序列時,返回 true。 System.out.println("tell if a contains appointed String: "+a.contains("bcd")); System.out.println("----------------------------------"); // 將此字串與指定的 StringBuffer 或者charsequence比較。 System.out.println("tell if a equals to a StringBuffer or a charsequence: "+a.contentEquals("abcd")); System.out.println("----------------------------------"); //測試該字串是否以指定字尾sffix結束 System.out.println("tell a is end with appointed String: "+"\n"+a.endsWith("efg")+"\n"+a.endsWith("df")); System.out.println("----------------------------------"); //判斷字串是否為空 System.out.println("tell a is empty"+a.isEmpty()); System.out.println("----------------------------------"); //輸出字串的長度: System.out.println("the length of appointed String is: "+c.length()); System.out.println("----------------------------------"); //用指定的子串替換字串中的特定的子串 System.out.println("the pre d is: "+d+"\n"+"the followed d is: "+d.replace("ab", "ef")); System.out.println("----------------------------------"); } }

輸出結果為:

The result of a compare to b is 32
The result of b compare to a is 66
----------------------------------
a compare to b ignoring case : 0
----------------------------------
connect b to the end of a: abcdefgAbcdefg
----------------------------------
tell if a contains appointed String: true
----------------------------------
tell if a equals  to a StringBuffer or a charsequence: false
----------------------------------
tell a is end with appointed String: 
true
false
----------------------------------
tell a is emptyfalse
----------------------------------
the length of appointed String is: 4
----------------------------------
the pre d is: abcabcabcabc
the followed d is: efcefcefcefc
----------------------------------


全的類介紹參考可參考網站易百