Java子字串

Java String substring()方法用於將String的一部分作為新String返回。此方法始終返回一個新的String,並且原始字串值不受影響,因為String在java中是不可變的。

Java String substring()方法已重載,有兩個變體。

  • substring(int beginIndex) - 此方法返回一個新字串,該字串是此字串的子字串。子字串以指定索引處的字元開頭,並延伸到此字串的末尾。

  • substring(int beginIndex, int endIndex) - 此方法返回一個新字串,該字串是此字串的子字串。子字串從指定的beginIndex開始,並擴展到索引endIndex-1處的字元。因此子字串的長度為(endIndex - beginIndex)

Java子字串要點

  • 如果滿足以下任何條件,則兩個字串子字串方法都可以拋出IndexOutOfBoundsException異常。

    • 如果beginIndex為負數
    • endIndex大於此String對象的長度
    • beginIndex大於endIndex
  • beginIndex是包含的,endIndex在兩個子字串方法中都是不包含的。

Java子字串示例

下麵是java中子字串的簡單程式。


public class StringSubstringExample {

    public static void main(String[] args) {
        String str = "www.xuhuhu.com";
        System.out.println("Last 4 char String: " + str.substring(str.length() - 4));
        System.out.println("First 4 char String: " + str.substring(0, 4));
        System.out.println("website name: " + str.substring(4, 14));
    }
}

執行上面示例代碼,得到以下結果 -

Last 4 char String: .com
First 4 char String: www.
website name: xuhuhu.com

在Java中使用子串檢查回文

可以使用substring來檢查一個String是否是回文。


public class StringPalindromeTest {
    public static void main(String[] args) {
        System.out.println(checkPalindrome("abcba"));
        System.out.println(checkPalindrome("XYyx"));
        System.out.println(checkPalindrome("999232999"));
        System.out.println(checkPalindrome("CCCCC"));
    }

    private static boolean checkPalindrome(String str) {
        if (str == null)
            return false;
        if (str.length() <= 1) {
            return true;
        }
        String first = str.substring(0, 1);
        String last = str.substring(str.length() - 1);
        if (!first.equals(last))
            return false;
        else
            return checkPalindrome(str.substring(1, str.length() - 1));
    }
}

執行上面示例代碼,得到以下結果 -

true
false
true
true

在上面示例代碼中,檢查第一個字母和最後一個字母是否相同。如果它們不相同,則返回false。否則,通過傳遞刪除了第一個和最後一個字母的子字串來遞歸地再次調用該方法。


上一篇: java中方法重載和方法重寫的區別 下一篇:無