String類的常用方法簡介
- char cahrAt(int index)方法,使用charAt方法輸入一個int index值即可返回索引值的字符.
String s1 = "abcdefgh";
System.out.println(s1.charAt(3));
- int comepareTo(String anotherString)方法,按照字典順序進行比較兩個字符串。比較字符串時,從第一個字母開始比較,若一樣則比較下一個字符。
String s2 = "abc";
String s3 = "abf";
System.out.println(s2.compareTo(s3));
String s2 = "abc";
String s3 = "aff";
System.out.println(s2.compareTo(s3));
- String concat(String str)方法,將指定字符串連接到此字符串的結尾.
String s4 = "abc";
String s5 = "def";
System.out.println(s4.concat(s5));
- boolean contains(CharSequences s)方法,判斷此字符串是否包含指定的字符串,如果是則返回爲true否則返回false。
String s4 = "abc";
System.out.println(s4.contains("ab"));
System.out.println(s4.contains("e"));
- boolean startsWith(String str)和boolean endWith(String str)方法,分別是判斷字符串是否是以指定的字符串開始或結尾
String s4 = "abc";
System.out.println(s4.startsWith("ab"));
System.out.println(s4.endsWith("c"));
- boolean isEmpty(),判斷此字符串是否爲空
String s5 = "";
System.out.println(s5.isEmpty());
- byte[] getTypes()使用平臺默認字符集將此String編碼爲byte序列,並將結果存儲在一個新的byte數組中
String s7 = "abcde";
byte[] bytes = s7.getBytes();
for (byte b:
bytes) {
System.out.println(b);
}
- int hashcode(),返回此字符串的哈希碼
String s7 = "abcde";
System.out.println(s7.hashCode());
- int indexOf(int ch),返回指定字符在此字符串中第一次出現處的索引
int indexOf(String str),返回指定子字符串在此字符串中第一次出現處的索引
String s7 = "abcde";
System.out.println(s7.indexOf(99));
System.out.println(s7.indexOf("c"));
- int indexOf(int ch, int fromIndex),返回在此字符串中第一次出現指定字符處的索引,從指定的索引開始搜索。
int indexOf(String str,int fromIndex),返回在此字符串中第一次出現指定子字符串的索引,從指定的索引開始搜索。
String s8 = "abcdeabcde";
System.out.println(s8.indexOf(100,4));
System.out.println(s8.indexOf("d",4));
- int lenth(),返回字符串的長度
String s8 = "abcdeabcde";
System.out.println(s8.length());
- String replace(char oldChar,char new Char),返回一個新的字符串,它是通過用 newChar 替換此字符串中出現的所有 oldChar 得到的
String s9 = "abc";
String s10 = "def";
System.out.println(s9.replace("bc",s10));
- char[] toCharArray(),將此字符串轉換爲一個新的字符數組
String s10 = "def";
char[] chars = s10.toCharArray();
for (char c :
chars) {
System.out.println(c);
}
- String subString(int beginIndex),返回一個新的字符串,是此字符串的一個子字符串,返回的新的字符串包含頭的開始部分
String subString(int brginIndex,int endIndex),返回一個新的字串,是截取的此字符串的一個子字符串,返回的新的字符串包含頭但是不包含尾
String s11 = "abcdefgh";
System.out.println(s11.substring(1));
System.out.println(s11.substring(1,3));