本文共 2143 字,大约阅读时间需要 7 分钟。
Java 1.4 introduced the CharSequence interface and String implements this interface. This is the only reason for the implementation of subSequence() method in String class. Internally it invokes the method.
Java 1.4引入了CharSequence接口,而String实现了此接口。 这是在String类中实现subSequence()方法的唯一原因。 在内部,它调用方法。
Below code snippet is from String subSequence method implementation.
下面的代码片段来自String subSequence方法的实现。
public CharSequence subSequence(int beginIndex, int endIndex) { return this.substring(beginIndex, endIndex);}
String subSequence method returns a character sequence that is a subsequence of this sequence. An invocation of this method of the form str.subSequence(begin, end)
behaves in exactly the same way as the invocation of str.substring(begin, end)
.
字符串subSequence方法返回一个字符序列,该字符序列是该序列的子序列。 形式的这种方法的调用str.subSequence(begin, end)
的行为以完全相同的方式的调用str.substring(begin, end)
。
Below is a simple Java String subSequence method example.
下面是一个简单的Java String subSequence方法示例。
StringSubsequence.java
StringSubsequence.java
package com.journaldev.examples;public class StringSubsequence { /** * This class shows usage of String subSequence method * * @param args */ public static void main(String[] args) { String str = "www.journaldev.com"; System.out.println("Last 4 char String: " + str.subSequence(str.length() - 4, str.length())); System.out.println("First 4 char String: " + str.subSequence(0, 4)); System.out.println("website name: " + str.subSequence(4, 14)); // substring vs subSequence System.out.println("substring == subSequence ? " + (str.substring(4, 14) == str.subSequence(4, 14))); System.out.println("substring equals subSequence ? " + (str.substring(4, 14).equals(str.subSequence(4, 14)))); }}
Output of the above String subSequence example program is:
上面的String subSequence示例程序的输出为:
Last 4 char String: .comFirst 4 char String: www.website name: journaldevsubstring == subSequence ? falsesubstring equals subSequence ? true
There is no benefit in using subSequence
method. Ideally, you should always use String substring method.
使用subSequence
方法没有任何好处。 理想情况下,应始终使用String子字符串方法。
翻译自:
转载地址:http://gqlzd.baihongyu.com/