且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

String.subString()和String.subSequence()之间的区别是什么

更新时间:2022-06-16 02:24:09

使用 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";