String、Stringbuilder和StringBuffer常用方法
阿新 • • 發佈:2018-05-25
case 位置 string對象 ase system span builder println lsi
1、String類:
//根據字符串直接量來創建一個String對象。新創建的對象是該參數字符串的副本。 String s = new String("String Test"); String s1 = new String("abcdef"); String s2 = new String("abcdefgh"); String s3 = new String("hgfedcba"); String s4 = new String("abcdef"); //比較s1和s2的大小 較長字符串前面部分正好是較短字符串,則返回它們的長度差 int result = s1.compareTo(s2); System.out.println(result);// -2 //比較s1和s3的大小 不想等,返回第一個不相等的字符差 int result1 = s1.compareTo(s3); System.out.println(result1); // -7 //比較s1和s3的大小 int result2 = s1.compareTo(s4 ); System.out.println(result2); // 0 //將指定字符串和制定對象進行比較 boolean bs = s1.equals("abcdef"); //忽略大小寫比較 boolean bss = s1.equalsIgnoreCase("ABCDEF"); //找出s1字符串第一次出現的位置s2.indexOf(s1); //找出s1字符串從fromIndex開始後第一次出現的位置 s2.indexOf(s1,5); //找出s1字符串最後一次出現的位置 s2.lastIndexOf(s1); //字符串長度 s2.length(); //將字符串中的第一個ab替換成bc s2.replace("ab","bc"); //獲取從2位置開始到結束的子字符串 s2.substring(2); //獲取從2位置開始到7結束的子字符串 s2.substring(2,7); //大寫轉小寫 String upperCaseS2 = s2.toUpperCase(); System.out.println(upperCaseS2);//小寫轉大寫 upperCaseS2.toLowerCase(); //將int類型轉換成String int age = 5; System.out.println(String.valueOf(age));
2、StringBuilder類:
//定義 StringBuilder sb = new StringBuilder(); //追加字符串 sb.append("java"); //插入 sb.insert(0,"hello"); // hellojava //替換 sb.replace(5,6,"B"); // helloBava //刪除 sb.delete(5,6); // helloava //sb的長度 System.out.println(sb.length()); // 8 //sb的容量,通常比length大 System.out.println(sb.capacity()); // 16
3、Stringbuffer類:
Stringbuffer與StringBuilder的用法完全相同,只是Stringbuffer是線程安全的。
String、Stringbuilder和StringBuffer常用方法