String.subString()和String.subSequence()之间的区别是什么
String.subSequence()
具有以下javadoc:
String.subSequence()
has the following javadoc:
返回a新的字符序列,是
序列的子序列。
Returns a new character sequence that is a subsequence of this sequence.
调用此方法的形式
str.subSequence(begin, end)
的行为方式与调用完全相同
behaves in exactly the same way as the invocation
str.substring(begin, end)
定义此方法,以便String类可以实现
CharSequence接口。
This method is defined so that the String class can implement the CharSequence interface.
任何人都可以解释一下吗?
Can anyone explain?
使用 str.subSequence(开始,结束)
返回 CharSequence ,这是字符串的只读形式表示为一系列字符。
例如:
Using str.subSequence(begin, end)
returns a CharSequence which is a read only form of the string represented as a sequence of chars.
For Example:
String string = "Hello";
CharSequence subSequence = s.subSequence(0, 5);
它只读,因为你不能改变字符
在 CharSequence
内,无需实例化 CharSequence
的新实例。
Its read only in the sense that you can't change the chars
within the CharSequence
without instantiating a new instance of a CharSequence
.
如果你必须使用 str.subSequence(开始,结束)
,你可以将结果转换为字符串
:
If you have to use str.subSequence(begin, end)
, you can cast the result to a String
:
String string = "Hello";
String subSequence = (String) s.subSequence(0, 5);
并使用所有正常的 String
运算符 subSequence + =World;
and use all the normal String
operators like subSequence += " World";