Java基礎-----String類常用方法
String類的判斷功能
1、boolean equals(Object obj):比較字串的內容是否相同,區分大小寫。
2、boolean equalsIgnoreCase(String str):比較字串的內容是否相同,忽略大小寫。
3、boolean contains(String str):判斷大字串中是否包含小字串。
4、boolean startsWith(String str):判斷字串是否以某個指定的字串開頭。
5、boolean endsWith(String str):判斷字串是否以某個指定的字串結尾。
6、boolean isEmpty():判斷字串是否為空。
String類的獲取功能
1、int length():獲取字串的長度。
2、char charAt(int index):獲取指定索引位置的字元。
3、int indexOf(int ch):返回指定字元在此字串中第一次出現處的索引。
4、int index(String str):返回指定字串在此字串中第一次出現處的索引。
5、int indexOf(int ch, int fromIndex):返回指定字元在此字串中從指定位置後第一次出現處的索引。
6、String subString(int start):從指定位置開始擷取字串,預設到未尾。
String subString(int start,int end):從指定位置開始到指定位置結束擷取字串。
字串的遍歷:
package java基礎;
public class Demo4_String {
public static void main(String[] args) {
String s1 = "abcdef";
for (int i = 0; i < s1.length(); i++) {
System.out.println(s1.charAt(i));
}
}
}
String類的轉換功能
1、byte[] getBytes():把字串轉換成位元組陣列。
2、char[] toCharArray():把字串轉換為字元陣列。
3、static String valueOf(char[] chs):把字元陣列轉成字串。
4、static String valueOf(int i):把int型別的資料轉換成字串。
注意:String類的valueOf方法可以把任意型別的資料轉換成字串。
1、String to():把字串轉成小寫。
2、String toUpperCase():把字串轉成大寫。
3、String concat(String str):把字串拼接。
package java基礎;
public class Demo5_StringMethod {
public static void main(String[] args) {
String s1 = "abc";
byte[] arr = s1.getBytes();
for (int i = 0; i < arr.length; i++ ) {
System.out.print(arr[i] + " ");
}
System.out.println();
String s2 = "好好學習";
byte[] arr2 = s2.getBytes();//通過gbk碼錶將字串轉換成位元組陣列
for (int i = 0; i < arr2.length; i++) {//編碼:把我們看的懂轉換為計算機看的懂
System.out.print(arr2[i]);//gbk碼錶一箇中文代表兩個位元組,
} //gbk碼錶特點,中文的第一個位元組肯定是負數。
char[] arr3 = s1.toCharArray();
for (int i =0; i < arr3.length; i++) {
System.out.println(arr3[i]);
}
String s3 = String.valueOf(arr3);//底層是由String類的構造方法完成的
System.out.println(s3);
String s4 = String.valueOf(97);
System.out.println(s4 + " " + s4.length());
char c = 97;
System.out.println(c);
Person p = new Person("xiao",18);
String str = String.valueOf(p);
System.out.println(str);
System.out.println("-----------------------");
String str1 = "abcd";
String stra = str1.toUpperCase();
System.out.println(stra);
System.out.println(str1 + stra);//用+拼接字串更強大,可以用字串與任意型別相加。
System.out.println(str1.concat(stra));//concat方法呼叫的和傳入的都必須是字串。
}
}
package java基礎;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
}
把一個字串的首字母轉成大寫,其餘為小寫。
鏈式程式設計:只要保證每次呼叫完方法返回的是物件,就可以繼續呼叫。
package java基礎;
public class Test {
public static void main(String[] args) {
String s = "wOHIIJLJLHLH";
s = s.substring(0,1).toUpperCase().concat(s.substring(1).toLowerCase());
System.out.println(s);
}
}
把陣列轉換成字串
package java基礎;
public class Test2 {
public static void main(String[] args) {
int[] arr = {1,2,3};
String str = "[";
for (int i = 0; i < arr.length; i++) {
if (i == arr.length -1) {
str += arr[i] + "]";
} else {
str += arr[i] + ", ";
}
}
System.out.println(str);
}
}
執行結果如下: