在java編程中,String類中的方法是經常要用到的。下面通過一個程序給大家介紹一下在String類中10個常用的方法:
package com.dr.TinySK;
import java.lang.String;
public class Text {
public static void main(String [] args){
//(1)public String concat(String str);將指定字符串連接到此字符串的結尾。
//如果參數字符串的長度為 0,則返回此 String 對象。
//否則,創建一個新的 String 對象,用來表示由此 String 對象表示的字符序列和參數字符串表示的字符序列連接而成的字符序列。
String s="abc";
String a="123";
System.out.println(a);
a=a.concat(s);
System.out.println(a);
/*(2)public String replace(CharSequence target,CharSequence replacement);
返回一個新的字符串,它是通過用 newChar 替換此字符串中出現的所有 oldChar 得到的。
如果 oldChar 在此 String 對象表示的字符序列中沒有出現,則返回對此 String 對象的引用。
否則,創建一個新的 String 對象,它所表示的字符序列除了所有的 oldChar 都被替換為 newChar 之外,
與此 String 對象表示的字符序列相同。 */
String e1="hahahaha";
System.out.println(e1);
e1=e1.replace('a', 'e');
System.out.println(e1);
//(3)public boolean contains(CharSequence s);當且僅當此字符串包含指定的 char 值序列時,返回 true。
boolean e2=false;
String aa="abcdef";
String bb="def";
e2=aa.contains(bb);
System.out.println(e2);
//(4)public int length() ;返回此字符串的長度。長度等于字符串中 Unicode 代碼單元的數量。
String e3="abcdefghigklmn";
System.out.println(e3.length());
// (5)public boolean isEmpty();當且僅當 length() 為 0 時返回 true。
String e4="110";
boolean e5=e4.isEmpty();
System.out.println(e5);
//(6)public String[] split(String regex);
//根據給定正則表達式的匹配拆分此字符串。
//該方法的作用就像是使用給定的表達式和限制參數 0 來調用兩參數 split 方法。
//因此,所得數組中不包括結尾空字符串
String e6="boo:and:foo";
String []e7=e6.split(":");
System.out.println(e7[0]);
System.out.println(e7[1]);
System.out.println(e7[2]);
//public String substring(int beginIndex,
// int endIndex)返回一個新字符串,它是此字符串的一個子字符串。
//該子字符串從指定的 beginIndex 處開始,直到索引 endIndex - 1 處的字符。
//因此,該子字符串的長度為 endIndex-beginIndex。
System.out.println("hamburger".substring(4, 8) );
//returns "urge"
System.out.println("smiles".substring(1, 5) );
//returns "mile"
//(7)public static String format(String format,
//Object... args)使用指定的格式字符串和參數返回一個格式化字符串。
//始終使用 Locale.getDefault() 返回的語言環境。
String e8="123456";
char c[]=e8.toCharArray();
System.out.println(c[2]);
//c[2]的值為3;
//(8)public boolean startsWith(String prefix)測試此字符串是否以指定的前綴開始。
String e9="#123456789";
System.out.println(e9.startsWith("#"));
//(9)public String toLowerCase()使用默認語言環境的規則將此 String 中的所有字符都轉換為小寫。
//這等效于調用 toLowerCase(Locale.getDefault())。
String e10="abcDEDF";
System.out.println(e10.toUpperCase());
//(10)public String trim()返回字符串的副本,忽略前導空白和尾部空白。
String e11=" abcdef";
System.out.println(e11);
System.out.println(e11.trim());
}
}
程序運行結果如圖: