Java中,String類是一個非常重要的基礎類,它表示文本字元串。String類的實例是不可變的,也就是說,一旦創建,它們的值就不能被改變。在本篇文章中,我們將介紹Java String類的常用方法。
一、獲取字元串長度
要獲取String對象所包含的字元數(長度),可以使用length()方法。
String str = "hello"; int length = str.length(); System.out.println(length); // 輸出5
二、獲取指定位置的字元
要獲取String對象指定位置的字元,可以使用charAt()方法。
String str = "hello"; char ch = str.charAt(1); System.out.println(ch); // 輸出'e'
三、獲取子字元串
要獲取String對象的子串,可以使用substring()方法。
String str = "hello"; String sub = str.substring(1, 4); System.out.println(sub); // 輸出"ell"
上面的代碼中,substring()方法的第一個參數是子字元串的起始位置,從0開始;第二個參數是子字元串的結束位置,不包含該位置的字元。
四、連接字元串
要將多個字元串連接起來,可以使用”+”操作符或者concat()方法。
String str1 = "hello"; String str2 = "world"; String str = str1 + " " + str2; System.out.println(str); // 輸出"hello world"
String str1 = "hello"; String str2 = "world"; String str = str1.concat(" ").concat(str2); System.out.println(str); // 輸出"hello world"
五、查找子串
要在一個字元串中查找指定的子串,可以使用indexOf()或者lastIndexOf()方法。
String str = "hello world"; int index = str.indexOf("world"); System.out.println(index); // 輸出6
上面的代碼中,indexOf()方法返回子字元串在原字元串中第一次出現的位置。
String str = "hello world"; int index = str.lastIndexOf("o"); System.out.println(index); // 輸出7
lastIndexOf()方法返回子字元串在原字元串中最後一次出現的位置。
六、替換字元串
要用新的字元串替換一個字元串中的舊字元串,可以使用replace()方法。
String str = "hello world"; String newStr = str.replace("world", "java"); System.out.println(newStr); // 輸出"hello java"
七、去除空白字元
要去除字元串中的空白字元,可以使用trim()方法。
String str = " hello world "; String newStr = str.trim(); System.out.println(newStr); // 輸出"hello world"
上面的代碼中,trim()方法會去除字元串的開頭和結尾的空白字元。
八、大小寫轉換
要將字元串的大小寫轉換,可以使用toLowerCase()和toUpperCase()方法。
String str = "Hello World"; String lower = str.toLowerCase(); String upper = str.toUpperCase(); System.out.println(lower); // 輸出"hello world" System.out.println(upper); // 輸出"HELLO WORLD"
九、判斷開頭和結尾
要判斷一個字元串是否以指定的子串開頭或結尾,可以使用startsWith()和endsWith()方法。
String str = "hello world"; boolean startsWith = str.startsWith("hello"); boolean endsWith = str.endsWith("world"); System.out.println(startsWith); // 輸出true System.out.println(endsWith); // 輸出true
結論
在本篇文章中,我們介紹了Java String類的常用方法,這些方法能夠滿足程序開發中常見的字元串操作需求。
原創文章,作者:YFIM,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/131110.html