String str=“We are students” Int size=Str.length();
indexOf(); 方法返回的是搜索的字符或字符串首次出現的位置; lastIndexOf(); 方法返回的是搜索的字符或字符串最后一次出現的位置;
public class PI { public static void main(String[] args) { String str="We are students"; int size=str.indexOf("a"); int size2=str.lastIndexOf(""); System.out.結果:
zhu:如果lastIndexOf()方法中的參數時空字符串“”(沒有空格),則返回的結果與調用該字符串的length()方法的結果相同。charAt();方法可以將指定索引處的字符返回。
“` public class PI { public static void main(String[] args) { String str=”Hello world”; char mychar=str.charAt(6); System.out.println(“字符串str中索引位置是5的字符為:”+mychar); } } 結果為:
substring()方法可對字符串進行截取,被兩種不同的方法重載,來滿足不同的需求。 substring(int beginIndex) 該方法返回的是從指定的索引位置開始截取直到該字符串結尾 String str=”Hello world”; String sub=str.substring(3);//獲取字符串,此時sub值為 lo world substring(int beginIndex,int endIndex)該方法返回的是從字符串某一索引位置開始截取到某一位置結束的子串
public class PI { public static void main(String[] args) { String str=”Hello world”; String sub=str.substring(0,3); System.out.println(sub); }} 結果為:Hel
trim()方法返回字符串的副本,忽略前導空格和尾部空格 str.trim();//str為任意字符串對象
replace()方法可實現將指定的字符串或字符替換成新的字符串或字符。 Str.replace(char oldChar,char newChar)//oldChar 要替換的舊字符或字符串,newChar 要替換的新字符或字符串 String str=”address”; String newstr=str.replace(“a”,”A”);//將str中a替換為A;
startsWith()方法與endWith()方法用于判斷字符串是否已指定的內容開始或結束。 例:String num=”22045612”; boolean b=num.startsWith(“22”);//判斷num是否以22開頭 boolean b=num.endsWith(“23”);//判斷num是否以23結尾 結果:true false
==比較的是兩個字符串地址是否相等 要比較兩個字符串內容是否相等,用equala()方法和equalsIgnoreCase()方法。 equala()方法比較時區分大小寫,equalsIgnoreCase()方法忽略大小寫,返回結果都為boolean型
public class PI { public static void main(String[] args) { String s1=”abc”; String s2=”ABC”; boolean b=s1.equals(s2); boolean b2=s1.equalsIgnoreCase(s2); System.out.println(s1+” equals “+s2+”: “+b); System.out.println(s1+” equalsIgnoreCase”+s2+”: “+b2); } } } 結果:abc equals ABC: false abc equlsIgnoreCaseABC: 按e
compareTo()方法比較基于字符串中各個字符串中各個字符的Unicode值,按照字典順序將此String對象表示的字符序列與參數字符串所表現出來的字符序列進行比較。如果String對象在參數字符串前,則返回一個負整數,如果在后面,返回一個正整數,若想等,則返回0. str.compareTo(String otherstr);
例: String str=new String(“b”); String str2=new String(“a”); System.ut.println(str+”compareTo”+str2+”:”+str.compareTo(str2)); 結果為:b compareTo a:1;
toLowerCase();方法可將字符串中的所有字符從大寫字母改寫為小寫字母; str. toLowerCase(); toUpperCase();方法可將字符串中的所有字符從小寫字母改寫為大寫字母; str. toUpperCase (); 進行轉化時,數字或者非字符不受影響
Split()方法可以使字符串按指定的分割符或字符串對內容進行分割,并將分割后的結果存放在字符串數組中。
結果為:abc def ghi jkl abc def,ghi,jkl
format()用于創建格式化的字符串 str.format(String format,Object…args) format(Local1,String format,Object…args) format:格式字符串 args:格式字符串中由格式說明符引用的參數。 1:格式化過程中要應用的語言環境。如果1為null,則不進行本地化。
日格式化 %te 一個月中的某一天(1~31) 2
例如:
時間格式化:
格式化常見的日期時間組合
常規類型格式化
正則表達式通常被用于判斷語句中,用來檢查某一字符是否滿足某一格式 [正則表達式]http://www.runoob.com/regexp/regexp-syntax.html
大大提高了頻繁增加字符串的效率 相關知識: http://wenku.baidu.com/view/a41b086058fb770bf78a559c.html
新聞熱點
疑難解答