本文共 3297 字,大约阅读时间需要 10 分钟。
Java String substring() method returns the substring of this string. This method always returns a new string and the original string remains unchanged because .
Java String substring()方法返回此字符串的子字符串。 此方法始终返回一个新字符串,而原始字符串则保持不变,因为 。
Java String substring method is overloaded and has two variants.
Java String子字符串方法已重载,并且具有两个变体。
substring(int beginIndex)
: This method returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string. substring(int beginIndex)
:此方法返回一个新字符串,该字符串是该字符串的子字符串。 子字符串以指定索引处的字符开头,并延伸到该字符串的末尾。 substring(int beginIndex, int endIndex)
: The substring begins at the specified beginIndex and extends to the character at index endIndex – 1. Thus the length of the substring is (endIndex – beginIndex). substring(int beginIndex, int endIndex)
:子字符串从指定的beginIndex开始,并扩展到索引endIndex – 1处的字符。因此,子字符串的长度为(endIndex – beginIndex)。 IndexOutOfBoundsException
if any of the below conditions met. IndexOutOfBoundsException
。 Here is a simple program for the substring in java.
这是Java中子字符串的简单程序。
package com.journaldev.util;public class StringSubstringExample { public static void main(String[] args) { String str = "www.journaldev.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)); }}
Output of the above substring example program is:
上面的子字符串示例程序的输出为:
Last 4 char String: .comFirst 4 char String: www.website name: journaldev
We can use the substring() method to check if a String is a palindrome or not.
我们可以使用substring()方法来检查String是否是回文。
package com.journaldev.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)); }}
Here we are checking if the first letter and the last letter is the same or not. If they are not the same, return false. Otherwise, call the method again recursively passing the substring with the first and last letter removed.
在这里,我们检查第一个字母和最后一个字母是否相同。 如果它们不相同,则返回false。 否则,再次调用该方法以递归方式传递子字符串,并删除第一个和最后一个字母。
Reference:
参考:
翻译自:
转载地址:http://ellzd.baihongyu.com/