本篇內容主要講解“Java中String類常用方法有哪些”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Java中String類常用方法有哪些”吧!
注意:
對于內置類型,==比較的是變量中的值;對于引用類型 , == 比較的是引用中的地址。
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 10;
// 對于基本類型變量,==比較兩個變量中存儲的值是否相同
System.out.println(a == b); // false
System.out.println(a == c); // true
// 對于引用類型變量,==比較兩個引用變量引用的是否為同一個對象
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = new String("world");
String s4 = s1;
System.out.println(s1 == s2); // false
System.out.println(s2 == s3); // false
System.out.println(s1 == s4); // true
}按照字典序進行比較(字典序:字符大小的順序)
String類重寫了父類Object中equals方法,Object中equals默認按照==比較,String重寫equals方法后,按照 如下規則進行比較,比如: s1.equals(s2)
String中的equals方法分析:
public boolean equals(Object anObject) {
// 1. 先檢測this 和 anObject 是否為同一個對象比較,如果是返回true
if (this == anObject) {
return true;
}
// 2. 檢測anObject是否為String類型的對象,如果是繼續比較,否則返回false
if (anObject instanceof String) {
// 將anObject向下轉型為String類型對象
String anotherString = (String)anObject;
int n = value.length;
// 3. this和anObject兩個字符串的長度是否相同,是繼續比較,否則返回false
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
// 4. 按照字典序,從前往后逐個字符進行比較
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}比較示例代碼:
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = new String("Hello");
// s1、s2、s3引用的是三個不同對象,因此==比較結果全部為false
System.out.println(s1 == s2); // false
System.out.println(s1 == s3); // false
// equals比較:String對象中的逐個字符
// 雖然s1與s2引用的不是同一個對象,但是兩個對象中放置的內容相同,因此輸出true
// s1與s3引用的不是同一個對象,而且兩個對象中內容也不同,因此輸出false
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // false
}按照字典序進行比較
與equals不同的是,equals返回的是boolean類型,而compareTo返回的是int類型。具體比較方式:
先按照字典次序大小比較,如果出現不等的字符,直接返回這兩個字符的大小差值
如果前k個字符相等(k為兩個字符長度最小值),返回值兩個字符串長度差值
public static void main(String[] args) {
String s1 = new String("abc");
String s2 = new String("ac");
String s3 = new String("abc");
String s4 = new String("abcdef");
System.out.println(s1.compareTo(s2)); // 不同輸出字符差值-1
System.out.println(s1.compareTo(s3)); // 相同輸出 0
System.out.println(s1.compareTo(s4)); // 前k個字符完全相同,輸出長度差值 -3
}與compareTo方式相同,但是忽略大小寫進行比較
public static void main(String[] args) {
String s1 = new String("abc");
String s2 = new String("ac");
String s3 = new String("ABc");
String s4 = new String("abcdef");
System.out.println(s1.compareToIgnoreCase(s2)); // 不同輸出字符差值-1
System.out.println(s1.compareToIgnoreCase(s3)); // 相同輸出 0
System.out.println(s1.compareToIgnoreCase(s4)); // 前k個字符完全相同,輸出長度差值 -3
}字符串查找也是字符串中非常常見的操作,String類提供的常用查找的方法,
| 方法 | 功能 |
|---|---|
| char charAt(int index) | 返回index位置上字符,如果index為負數或者越界,拋出 IndexOutOfBoundsException異常 |
| int indexOf(int ch) | 返回ch第一次出現的位置,沒有返回-1 |
| int indexOf(int ch, int fromIndex) | 從fromIndex位置開始找ch第一次出現的位置,沒有返回-1 |
| int indexOf(String str) | 返回str第一次出現的位置,沒有返回-1 |
| int indexOf(String str, int fromIndex) | 從fromIndex位置開始找str第一次出現的位置,沒有返回-1 |
| int lastIndexOf(int ch) | 從后往前找,返回ch第一次出現的位置,沒有返回-1 |
| int lastIndexOf(int ch, int fromIndex) | 從fromIndex位置開始找,從后往前找ch第一次出現的位置,沒有返 回-1 |
| int lastIndexOf(String str) | 從后往前找,返回str第一次出現的位置,沒有返回-1 |
| int lastIndexOf(String str, int fromIndex) | 從fromIndex位置開始找,從后往前找str第一次出現的位置,沒有返 回-1 |
public static void main(String[] args) {
String s = "aaabbbcccaaabbbccc";
System.out.println(s.charAt(3)); // 'b'
System.out.println(s.indexOf('c')); // 6
System.out.println(s.indexOf('c', 10)); // 15
System.out.println(s.indexOf("bbb")); // 3
System.out.println(s.indexOf("bbb", 10)); // 12
System.out.println(s.lastIndexOf('c')); // 17
System.out.println(s.lastIndexOf('c', 10)); // 8
System.out.println(s.lastIndexOf("bbb")); // 12
System.out.println(s.lastIndexOf("bbb", 10)); // 3
}注意:
上述方法都是實例方法,通過對象引用調用。
static String valueof() 數值轉字符串
Integer.parseInt() 字符串整形
Double.parseDouble() 字符串轉浮點型
public class Test {
public static void main(String[] args) {
// 值轉字符串
String s1 = String.valueOf(1234);
String s2 = String.valueOf(12.34);
String s3 = String.valueOf(true);
String s4 = String.valueOf(new Student("Hanmeimei", 18));
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println("=================================");
// 字符串轉數字
//Integer、Double等是Java中的包裝類型
int data1 = Integer.parseInt("1234");
double data2 = Double.parseDouble("12.34");
System.out.println(data1);
System.out.println(data2);
}
}
class Student{
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}執行結果:

String toUpperCase() 轉大寫
String toLowerCase() 轉小寫
這兩個函數只轉換字母。
public static void main(String[] args) {
String s1 = "hello";
String s2 = "HELLO";
// 小寫轉大寫
System.out.println(s1.toUpperCase());
// 大寫轉小寫
System.out.println(s2.toLowerCase());
}執行結果:

char[ ] toCharArray() 字符串轉數組
new String(數組引用) 數組轉字符串
public static void main(String[] args) {
String s = "hello";
// 字符串轉數組
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
System.out.print(ch[i]);
}
System.out.println();
// 數組轉字符串
String s2 = new String(ch);
System.out.println(s2);
}執行結果:

static String format( );
public static void main(String[] args) {
String s = String.format("%d-%d-%d", 2022, 8, 29);
System.out.println(s);
}執行結果:

使用一個指定的新的字符串替換掉已有的字符串數據,可用的方法如下:
| 方法 | 功能 |
|---|---|
| String replaceAll(String regex, String replacement) | 替換所有的指定內容 |
| String replaceFirst(String regex, String replacement) | 替換首個指定內容 |
代碼示例:
字符串的替換處理:
public static void main(String[] args) {
String str = "helloworld" ;
System.out.println(str.replaceAll("l", "_"));
System.out.println(str.replaceFirst("l", "_"));
}執行結果:

注意事項:
由于字符串是不可變對象, 替換不修改當前字符串, 而是產生一個新的字符串.
可以將一個完整的字符串按照指定的分隔符劃分為若干個子字符串。
可用方法如下:
| 方法 | 功能 |
|---|---|
| String[] split(String regex) | 將字符串全部拆分 |
| String[] split(String regex, int limit) | 將字符串以指定的格式,拆分為limit組 |
如果一個字符串中有多個分隔符,可以用"|"作為連字符.
代碼示例:
實現字符串的拆分處理
public static void main(String[] args) {
String str = "hello world hello rong";
String[] result = str.split(" ") ; // 按照空格拆分
for(String s: result) {
System.out.println(s);
}
System.out.println("==============");
String str1 = "xin&xin=xiang&rong";
String[] str2 = str1.split("&|=");//按照=和&拆分
for(String s: str2) {
System.out.println(s);
}
}執行結果:

代碼示例:
字符串的部分拆分
public static void main(String[] args) {
String str = "hello world hello rong" ;
String[] result = str.split(" ",2) ;
for(String s: result) {
System.out.println(s);
}
}執行結果:

有些特殊字符作為分割符可能無法正確切分, 需要加上轉義.
字符"|“,”*“,”+“,”."都得加上轉義字符,前面加上 “” .
而如果是 “” ,那么就得寫成 “\” ; 使用split來切分字符串時,遇到以反斜杠\作為切分的字符串,split后傳入的內容是\\,這么寫是因為第一和第三是個斜杠是字符串的轉義符。轉義后的結果是\,split函數解析的不是字符串而是正則,正則表達式中的\結果對應\,所以分隔反斜杠的時候要寫四個反斜杠。
代碼示例:
拆分IP地址
public static void main(String[] args) {
String str = "192.168.1.1" ;
String[] result = str.split("\\.") ;
for(String s: result) {
System.out.println(s);
}
}執行結果:

代碼中的多次拆分:
ppublic static void main(String[] args) {
//字符串多次拆封
String str = "xin&xin=xiang&rong";
String[] str1 = str.split("&");
for (int i = 0; i < str1.length; i++) {
String[] str2 = str1[i].split("=");
for (String x:str2) {
System.out.println(x);
}
}
String s = "name=zhangsan&age=18" ;
String[] result = s.split("&") ;
for (int i = 0; i < result.length; i++) {
String[] temp = result[i].split("=") ;
System.out.println(temp[0]+" = "+temp[1]);
}
}執行結果:

從一個完整的字符串之中截取出部分內容??捎梅椒ㄈ缦?:
| 方法 | 功能 |
|---|---|
| String substring(int beginIndex) | 從指定索引截取到結尾 |
| String substring(int beginIndex, int endIndex) | 截取部分內容 |
代碼示例:
public static void main(String[] args) {
String str = "helloworld" ;
System.out.println(str.substring(5));
System.out.println(str.substring(0, 5));
}執行結果:

注意事項:
索引從0開始
注意前閉后開區間的寫法, substring(0, 5) 表示包含 0 號下標的字符, 不包含 5 號下標,即(0,4)
去掉字符串中的左右空格,保留中間空格
trim 會去掉字符串開頭和結尾的空白字符(空格, 換行, 制表符等).
示例代碼:
public static void main(String[] args) {
String str = " hello world " ;
System.out.println("["+str+"]");
System.out.println("["+str.trim()+"]");
}執行結果:

isEmpty() 方法用于判斷字符串是否為空
示例代碼:
public static void main(String[] args) {
String str = "";
System.out.println(str.isEmpty());
}執行結果:

用于求字符串的長度
示例代碼:
public static void main(String[] args) {
String str = "xinxinxiangrong";
System.out.println(str.length());
}執行結果:

boolean startsWith(String prefix) 判斷字符串是否以某個字符串開頭的
boolean endWith(String sufix) 判斷字符串是否以某個字符串結尾的
示例代碼:
public static void main(String[] args) {
String str = "xinxinxianrong";
System.out.println(str.startsWith("xin"));
System.out.println(str.endsWith("rong"));
}執行結果:

判斷字符串中是否包含某個字符串
示例代碼:
public static void main(String[] args) {
String str = "xinxinxianrong";
System.out.println(str.contains("inx"));
}執行結果:

到此,相信大家對“Java中String類常用方法有哪些”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。