1 length()字符串的長度
String a = "Hello Word!"; System.out.println(a.length);
輸出的結果是字符串長度10。
2 charAt()截取一個字符
String a = "Hello Word"; System.out.println(a.charAt(1));
輸出的結果是字符串a的下標為1的字符e。
3 getchars()截取多個字符並由其他字符串接收
String a = "Hello Word"; char[] b = new char[10]; a.getChars(0, 5, b, 0); System.out.println(b);
輸出的結果為Hello,其中第一個參數0是要截取的字符串的初始下標(int sourceStart),第二個參數5是要截取的字符串的結束后的下一個下標(int sourceEnd)也就是實際截取到的下標是int sourceEnd-1,第三個參數是接收的字符串(char target[]),最后一個參數是接收的字符串開始接收的位置。
4 getBytes()將字符串變成一個byte數組
String a = "Hello Word"; byte b[] = a.getBytes(); System.out.println(new String(b));
輸出的結果為Hello Word的byte數組。
5 toCharArray()將字符串變成一個字符數組
String a = "Hello Word"; char[]b = a.toCharArray(); System.out.println(b);
輸出的結果為Hello Word字符數組。
6 equals()和equalsIgnoreCase()比較兩個字符串是否相等,前者區分大小寫,后者不區分
String a = "Hello Word"; String b = "hello word"; System.out.println(a.equals(b));
System.out.println(a.equalsIgnoreCase(b));
輸出的結果為第一條為false,第二條為true。
7 startsWith()和endsWith()判斷字符串是不是以特定的字符開頭或結束
String a = "Hello Word"; System.out.println(a.startsWith("ee")); System.out.println(a.endsWith("rd"));
輸出的結果第一條為false,第二條為true。
8 toUpperCase()和toLowerCase()將字符串轉換為大寫或小寫
String a = "Hello Word"; System.out.println(a.toUpperCase()); System.out.println(a.toLowerCase());
輸出的結果第一條為“HELLO WORD”,第二條為“hello word”。
9 concat() 連接兩個字符串
String a = "Hello Word"; String b = "你好"; System.out.println(b.concat(a));
輸出的結果為“你好Hello Word”。
10 trim()去掉起始和結束的空格
String a = " Hello Word "; System.out.println(a.trim());
輸出的結果為“Hello Word”。
11 substring()截取字符串
String a = "Hello Word"; System.out.println(a.substring(0, 5)); System.out.println(a.substring(6));
輸出的結果第一條為“Hello”,第一個參數0(beginIndex)是開始截取的位置,第二個參數5(endIndex)是截取結束的位置,輸出的結果第二條是“Word”,參數6(beginIndex)是開始截取的位置。
12 indexOf()和lastIndexOf()前者是查找字符或字符串第一次出現的地方,后者是查找字符或字符串最后一次出現的地方
String a = "Hello Word"; System.out.println(a.indexOf("o")); System.out.println(a.lastIndexOf("o"));
輸出的結果第一條是4,是o第一次出現的下標,第二條是7,是o最后一次出現的下標。
13 compareTo()和compareToIgnoreCase()按字典順序比較兩個字符串的大小,前者區分大小寫,后者不區分
String a = "Hello Word"; String b = "hello word"; System.out.println(a.compareTo(b)); System.out.println(a.compareToIgnoreCase(b));
輸出的結果第一條為-32,第二條為0,兩個字符串在字典順序中大小相同,返回0。
14 replace() 替換
String a = "Hello Word"; String b = "你好"; System.out.println(a.replace(a, b)); System.out.println(a.replace(a, "HELLO WORD"));
System.out.println(b.replace("你", "大家"));
輸出的結果第一條為“你好”,第二條為“HELLO WORD”,第三條為“大家好”。