Java String子序列

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 substring() method.

Java 1.4引入了CharSequence接口,而String实现了此接口。 这是在String类中实现subSequence()方法的唯一原因。 在内部,它调用substring()方法。

Java String子序列 (Java 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: .com
First 4 char String: www.
website name: journaldev
substring == subSequence ? false
substring equals subSequence ? true

There is no benefit in using subSequence method. Ideally, you should always use String substring method.

使用subSequence方法没有任何好处。 理想情况下,应始终使用String子字符串方法。

翻译自: https://www.journaldev.com/813/java-string-subsequence

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值