Java substring()方法详解:字符串截取的完整指南

Java的String substring()方法返回该字符串的子串。该方法始终返回一个新的字符串,原始字符串保持不变,因为Java中的String是不可变的。

Java的String substring()方法

Java的String子字符串方法是重载的,并且有两个变体。

  1. substring(int beginIndex): 此方法返回一个新的字符串,它是该字符串的一个子串。该子串从指定索引位置开始,并延伸到该字符串的末尾。
  2. substring(int beginIndex, int endIndex): 该子串从指定的beginIndex位置开始,延伸至endIndex – 1的字符。因此,子串的长度为(endIndex – beginIndex)。

字符串 substring() 方法的重要要点

如果满足以下任一条件,两种字符串子串方法都可能抛出IndexOutOfBoundsException异常:

  • beginIndex为负数
  • endIndex大于此String对象的长度
  • beginIndex大于endIndex

在两种子串方法中,beginIndex是包含的,而endIndex是排除的。

Java的String substring()示例

这是一个用Java编写的简单的字符串截取程序。

package com.Olivia.util;

public class StringSubstringExample {

	public static void main(String[] args) {
		String str = "www.scdev.com";
		System.out.println("最后4个字符的字符串: " + str.substring(str.length() - 4));
		System.out.println("前4个字符的字符串: " + str.substring(0, 4));
		System.out.println("网站名称: " + str.substring(4, 14));
	}
}

以上子字符串示例程序的输出结果是:

最后4个字符的字符串: .com
前4个字符的字符串: www.
网站名称: scdev

使用substring()方法检查回文

我们可以使用substring()方法来检查一个字符串是否是回文。

package com.Olivia.util;

public class StringPalindromeTest {
	public static void main(String[] args) {
		System.out.println(checkPalindrome("abcba"));
		System.out.println(checkPalindrome("XYyx"));
		System.out.println(checkPalindrome("871232178"));
		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));
	}
}

在这里我们正在检查第一个字母和最后一个字母是否相同。如果不相同,返回false。否则,递归调用该方法,传递去掉第一个和最后一个字母的子字符串。

您可以从我们的GitHub仓库中查看更多的字符串示例。

参考资料:Oracle API 文档

bannerAds