一、简介
String类实现了java.io.Serializable序列化接口, Comparable<String>比较接口, CharSequence 三个接口,String类是final的,因此不能被其他类继承。
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
//....
}
- String底层是通过char[]数组实现的,所有对字符串的操作都是通过字符数组来进行
/** The value is used for character storage. */
//value[]用于存储字符串内容,被final修饰,说明一旦创建就不可被修改
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0
- 序列化相关
/** use serialVersionUID from JDK 1.0.2 for interoperability */
//serialVersionUID是记录序列化的版本号
private static final long serialVersionUID = -6849794470754667710L;
/**
* Class String is special cased within the Serialization Stream Protocol.
*
* A String instance is written into an ObjectOutputStream according to
* <a href="{@docRoot}/../platform/serialization/spec/output.html">
* Object Serialization Specification, Section 6.2, "Stream Elements"</a>
*/
//serialPersistentFields用来存储需要被序列化的字段
private static final ObjectStreamField[] serialPersistentFields =
new ObjectStreamField[0];
- String构造方法
//初始化新创建的String对象,使其表示一个空字符序列。注意,这个构造函数的用法是不必要,因为字符串是不可变的。
public String() {
this.value = "".value;
}
//初始化新创建的String对象,使其表示参数的字符序列相同;换句话说,就是新创建的字符串是参数字符串的副本。除非一个
//需要显式复制original,使用这个构造函数不必要,因为字符串是不可变的
public String(String original) {
//value、hash都是String内部的私有属性
//直接将原始对象的值赋值给新创建的对象
this.value = original.value;
this.hash = original.hash;
}
//使用字符数组创建新字符串对象
//随后的修改字符数组不影响新创建的字符串
public String(char value[]) {
//使用Arrays进行数组的复制
this.value = Arrays.copyOf(value, value.length);
}
//从字符数组的offset位置字符开始,截取count个字符,创建一个新的字符串对象
//随后的修改字符数组不影响新创建的字符串
public String(char value[], int offset, int count) {
if (offset < 0) {
//越界异常
throw new StringIndexOutOfBoundsException(offset);
}
if (count <= 0) {
if (count < 0) {
//越界异常
throw new StringIndexOutOfBoundsException(count);
}
if (offset <= value.length) {
this.value = "".value;
return;
}
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
//使用Arrays.copyOfRange范围数组复制
this.value = Arrays.copyOfRange(value, offset, offset+count);
}
//使用的挺少的,暂不做详细分析
public String(int[] codePoints, int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count <= 0) {
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
if (offset <= codePoints.length) {
this.value = "".value;
return;
}
}
// Note: offset or count might be near -1>>>1.
if (offset > codePoints.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
final int end = offset + count;
// Pass 1: Compute precise size of char[]
int n = count;
for (int i = offset; i < end; i++) {
int c = codePoints[i];
if (Character.isBmpCodePoint(c))
continue;
else if (Character.isValidCodePoint(c))
n++;
else throw new IllegalArgumentException(Integer.toString(c));
}
// Pass 2: Allocate and fill in char[]
final char[] v = new char[n];
for (int i = offset, j = 0; i < end; i++, j++) {
int c = codePoints[i];
if (Character.isBmpCodePoint(c))
v[j] = (char)c;
else
Character.toSurrogates(c, v, j++);
}
this.value = v;
}
//用于检查字节数组的边界
private static void checkBounds(byte[] bytes, int offset, int length) {
if (length < 0)
throw new StringIndexOutOfBoundsException(length);
if (offset < 0)
throw new StringIndexOutOfBoundsException(offset);
if (offset > bytes.length - length)
throw new StringIndexOutOfBoundsException(offset + length);
}
//通过字节数组创建字符串,并制定编码集
public String(byte bytes[], int offset, int length, String charsetName)
throws UnsupportedEncodingException {
//如果没制定编码集,直接抛一个空指针异常
if (charsetName == null)
throw new NullPointerException("charsetName");
//检查字节数组是否越界
checkBounds(bytes, offset, length);
//底层调用StringDecoder.decode方法,在decode方法中如果编码集为空默认使用ISO-8859-1
this.value = StringCoding.decode(charsetName, bytes, offset, length);
}
//跟上面的方法类似,只是一个传入charsetName,一个传入Charset对象
public String(byte bytes[], int offset, int length, Charset charset) {
if (charset == null)
throw new NullPointerException("charset");
checkBounds(bytes, offset, length);
this.value = StringCoding.decode(charset, bytes, offset, length);
}
//不指定偏移量,直接从0开始
public String(byte bytes[], String charsetName)
throws UnsupportedEncodingException {
//调用String(byte bytes[], int offset, int length, String charsetName)
this(bytes, 0, bytes.length, charsetName);
}
//不指定偏移量,直接从0开始
public String(byte bytes[], Charset charset) {
//调用String(byte bytes[], int offset, int length, Charset charset)
this(bytes, 0, bytes.length, charset);
}
public String(byte bytes[], int offset, int length) {
checkBounds(bytes, offset, length);
//直接使用默认编码集ISO-8859-1进行解码
this.value = StringCoding.decode(bytes, offset, length);
}
//进一步简化传入参数,直接根据传入的字节数组创建字符串对象
public String(byte bytes[]) {
//调用String(byte bytes[], int offset, int length)
this(bytes, 0, bytes.length);
}
//根据字符串缓冲对象StringBuffer创建字符串,线程安全
public String(StringBuffer buffer) {
//使用到了synchronized同步块,保证线程安全
synchronized(buffer) {
//使用数组复制
this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
}
}
//根据字符串缓冲对象StringBuilder创建字符串,不加同步块,线程不安全
public String(StringBuilder builder) {
this.value = Arrays.copyOf(builder.getValue(), builder.length());
}
String(char[] value, boolean share) {
// assert share : "unshared not supported";
this.value = value;
}
二、常用API
【a】length()、isEmpty()、charAt()、getBytes()
//返回此字符串的长度
public int length() {
//字符数组的长度
return value.length;
}
//判断字符串是否为空
public boolean isEmpty() {
//判断字符数组的长度是否等于0
return value.length == 0;
}
//获取字符串指定索引的字符 索引从0开始,到value.length() - 1
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
//从dstBegin开始将字符串中的字符复制到dst,此方法不执行任何范围检查。
void getChars(char dst[], int dstBegin) {
//底层使用System.arraycopy实现数组拷贝
System.arraycopy(value, 0, dst, dstBegin, value.length);
}
//下面三个方法都是将指定的字符串将这个字符串编码为一个字节序列,并将结果存储到一个新的字节数组中。
public byte[] getBytes(String charsetName)
throws UnsupportedEncodingException {
if (charsetName == null) throw new NullPointerException();
return StringCoding.encode(charsetName, value, 0, value.length);
}
public byte[] getBytes(Charset charset) {
if (charset == null) throw new NullPointerException();
return StringCoding.encode(charset, value, 0, value.length);
}
public byte[] getBytes() {
return StringCoding.encode(value, 0, value.length);
}
【b】equals()字符串比较
//将此字符串与指定的对象进行比较
public boolean equals(Object anObject) {
//如果是当前对象,直接返回true
if (this == anObject) {
return true;
}
//判断是否是String类实例,如果是则挨个字符进行比较,如果不是直接返回false
if (anObject instanceof String) {
//强转为String对象
String anotherString = (String)anObject;
int n = value.length;
//判断比较的两个字符串长度是否一致
if (n == anotherString.value.length) {
//获取对应的字符数组
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
//循环字符数组,一个一个字符进行比较,只要碰到一个不相等,直接返回false,如果全部相同则返回true
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
//将StringBuffer对象与字符串对象进行比较
public boolean contentEquals(StringBuffer sb) {
//调用contentEquals(CharSequence cs)
return contentEquals((CharSequence)sb);
}
//非阻塞方法
private boolean nonSyncContentEquals(AbstractStringBuilder sb) {
char v1[] = value;
char v2[] = sb.getValue();
int n = v1.length;
if (n != sb.length()) {
return false;
}
for (int i = 0; i < n; i++) {
if (v1[i] != v2[i]) {
return false;
}
}
return true;
}
//
public boolean contentEquals(CharSequence cs) {
// Argument is a StringBuffer, StringBuilder
//AbstractStringBuilder的子类有StringBuffer和StringBuilder
if (cs instanceof AbstractStringBuilder) {
if (cs instanceof StringBuffer) {
//如果是与StringBuffer对象进行比较,加synchronized同步代码块
synchronized(cs) {
return nonSyncContentEquals((AbstractStringBuilder)cs);
}
} else {
//如果是与StringBuilder对象进行比较,不使用同步块控制
return nonSyncContentEquals((AbstractStringBuilder)cs);
}
}
// Argument is a String
if (cs instanceof String) {
return equals(cs);
}
// Argument is a generic CharSequence
char v1[] = value;
int n = v1.length;
if (n != cs.length()) {
return false;
}
//挨个字符进行比较
for (int i = 0; i < n; i++) {
if (v1[i] != cs.charAt(i)) {
return false;
}
}
return true;
}
//将字符串与另一个字符串进行比较,忽略大小写
public boolean equalsIgnoreCase(String anotherString) {
return (this == anotherString) ? true
: (anotherString != null)
&& (anotherString.value.length == value.length)
&& regionMatches(true, 0, anotherString, 0, value.length);
}
public boolean regionMatches(boolean ignoreCase, int toffset,
String other, int ooffset, int len) {
char ta[] = value;
int to = toffset;
char pa[] = other.value;
int po = ooffset;
// Note: toffset, ooffset, or len might be near -1>>>1.
if ((ooffset < 0) || (toffset < 0)
|| (toffset > (long)value.length - len)
|| (ooffset > (long)other.value.length - len)) {
return false;
}
while (len-- > 0) {
char c1 = ta[to++];
char c2 = pa[po++];
if (c1 == c2) {
continue;
}
if (ignoreCase) {
// If characters don't match but case may be ignored,
// try converting both characters to uppercase.
// If the results match, then the comparison scan should
// continue.
//尝试将两个字符都转换成大写
//如果结果匹配,那么比较扫描应该继续
char u1 = Character.toUpperCase(c1);
char u2 = Character.toUpperCase(c2);
if (u1 == u2) {
continue;
}
// Unfortunately, conversion to uppercase does not work properly
// for the Georgian alphabet, which has strange rules about case
// conversion. So we need to make one last check before
// exiting.
//做最后一次检查
if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
continue;
}
}
return false;
}
return true;
}
【c】startWith()、endWith()
//测试从指定索引开始的这个字符串的子字符串是否以指定的前缀开始
public boolean startsWith(String prefix, int toffset) {
char ta[] = value;
int to = toffset;
char pa[] = prefix.value;
int po = 0;
int pc = prefix.value.length;
// Note: toffset might be near -1>>>1.
if ((toffset < 0) || (toffset > value.length - pc)) {
return false;
}
while (--pc >= 0) {
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
}
//判断字符串是否与prefix开头
public boolean startsWith(String prefix) {
return startsWith(prefix, 0);
}
//判断字符串是否以指定的后缀suffix结束
public boolean endsWith(String suffix) {
return startsWith(suffix, value.length - suffix.value.length);
}
【d】compareTo()字符串比较
//将两个字符串中的每个字符的Unicode值进行比较
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
//获取两个字符串中长度较小的那一个长度进行循环遍历
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
//循环遍历最小长度lim,挨个拿出字符数组对应下标的值进行比较
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
//比较两个 字符串长度大小
return len1 - len2;
}
public static final Comparator<String> CASE_INSENSITIVE_ORDER
= new CaseInsensitiveComparator();
//私有的静态内部类CaseInsensitiveComparator,实现了Comparator比较接口,重写了compare()方法
private static class CaseInsensitiveComparator
implements Comparator<String>, java.io.Serializable {
// use serialVersionUID from JDK 1.2.2 for interoperability
private static final long serialVersionUID = 8575799808933029326L;
public int compare(String s1, String s2) {
int n1 = s1.length();
int n2 = s2.length();
int min = Math.min(n1, n2);
for (int i = 0; i < min; i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 != c2) {
c1 = Character.toUpperCase(c1);
c2 = Character.toUpperCase(c2);
if (c1 != c2) {
c1 = Character.toLowerCase(c1);
c2 = Character.toLowerCase(c2);
if (c1 != c2) {
// No overflow because of numeric promotion
return c1 - c2;
}
}
}
}
return n1 - n2;
}
/** Replaces the de-serialized object. */
//替换反序列化的对象
private Object readResolve() { return CASE_INSENSITIVE_ORDER; }
}
//忽略大小写的字符串比较
public int compareToIgnoreCase(String str) {
return CASE_INSENSITIVE_ORDER.compare(this, str);
}
【e】hashcode()
//返回此字符串的哈希码
//对象计算为: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
【f】indexOf()、lastIndexOf()
//通过值查询索引
public int indexOf(int ch) {
//调用indexOf(int ch, int fromIndex)
return indexOf(ch, 0);
}
//返回第一个匹配字符在字符串内的索引,在指定索引处开始搜索。
public int indexOf(int ch, int fromIndex) {
final int max = value.length;
if (fromIndex < 0) {
fromIndex = 0;
} else if (fromIndex >= max) {
//如果其实搜索索引大于字符串的总长度,直接返回-1,未找到
return -1;
}
//65536
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// handle most cases here (ch is a BMP code point or a
// negative value (invalid code point))
final char[] value = this.value;
//循环字符数组,挨个进行比较,返回第一个匹配到的元素的下标
//如果找不到,则返回-1
for (int i = fromIndex; i < max; i++) {
if (value[i] == ch) {
return i;
}
}
return -1;
} else {
return indexOfSupplementary(ch, fromIndex);
}
}
//处理(罕见的)带有附加字符的indexOf调用。
private int indexOfSupplementary(int ch, int fromIndex) {
if (Character.isValidCodePoint(ch)) {
final char[] value = this.value;
final char hi = Character.highSurrogate(ch);
final char lo = Character.lowSurrogate(ch);
final int max = value.length - 1;
for (int i = fromIndex; i < max; i++) {
if (value[i] == hi && value[i + 1] == lo) {
return i;
}
}
}
return -1;
}
//返回最后一次出现指定的字符在字符串中的索引
public int lastIndexOf(int ch) {
return lastIndexOf(ch, value.length - 1);
}
public int lastIndexOf(int ch, int fromIndex) {
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// handle most cases here (ch is a BMP code point or a
// negative value (invalid code point))
final char[] value = this.value;
int i = Math.min(fromIndex, value.length - 1);
//倒序循环字符数组,挨个比较,返回倒序匹配到的第一个元素对应的下标
//如果未找到,返回-1
for (; i >= 0; i--) {
if (value[i] == ch) {
return i;
}
}
return -1;
} else {
return lastIndexOfSupplementary(ch, fromIndex);
}
}
private int lastIndexOfSupplementary(int ch, int fromIndex) {
if (Character.isValidCodePoint(ch)) {
final char[] value = this.value;
char hi = Character.highSurrogate(ch);
char lo = Character.lowSurrogate(ch);
int i = Math.min(fromIndex, value.length - 2);
for (; i >= 0; i--) {
if (value[i] == hi && value[i + 1] == lo) {
return i;
}
}
}
return -1;
}
//返回第一个指定的子串匹配在字符串内的索引
public int indexOf(String str) {
return indexOf(str, 0);
}
public int indexOf(String str, int fromIndex) {
return indexOf(value, 0, value.length,
str.value, 0, str.value.length, fromIndex);
}
static int indexOf(char[] source, int sourceOffset, int sourceCount,
String target, int fromIndex) {
return indexOf(source, sourceOffset, sourceCount,
target.value, 0, target.value.length,
fromIndex);
}
static int indexOf(char[] source, int sourceOffset, int sourceCount,
char[] target, int targetOffset, int targetCount,
int fromIndex) {
if (fromIndex >= sourceCount) {
return (targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
char first = target[targetOffset];
int max = sourceOffset + (sourceCount - targetCount);
for (int i = sourceOffset + fromIndex; i <= max; i++) {
/* Look for first character. */
if (source[i] != first) {
while (++i <= max && source[i] != first);
}
/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
for (int k = targetOffset + 1; j < end && source[j]
== target[k]; j++, k++);
if (j == end) {
/* Found whole string. */
return i - sourceOffset;
}
}
}
return -1;
}
public int lastIndexOf(String str) {
return lastIndexOf(str, value.length);
}
public int lastIndexOf(String str, int fromIndex) {
return lastIndexOf(value, 0, value.length,
str.value, 0, str.value.length, fromIndex);
}
static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
String target, int fromIndex) {
return lastIndexOf(source, sourceOffset, sourceCount,
target.value, 0, target.value.length,
fromIndex);
}
static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
char[] target, int targetOffset, int targetCount,
int fromIndex) {
/*
* Check arguments; return immediately where possible. For
* consistency, don't check for null str.
*/
int rightIndex = sourceCount - targetCount;
if (fromIndex < 0) {
return -1;
}
if (fromIndex > rightIndex) {
fromIndex = rightIndex;
}
/* Empty string always matches. */
if (targetCount == 0) {
return fromIndex;
}
int strLastIndex = targetOffset + targetCount - 1;
char strLastChar = target[strLastIndex];
int min = sourceOffset + targetCount - 1;
int i = min + fromIndex;
startSearchForLastChar:
while (true) {
while (i >= min && source[i] != strLastChar) {
i--;
}
if (i < min) {
return -1;
}
int j = i - 1;
int start = j - (targetCount - 1);
int k = strLastIndex - 1;
while (j > start) {
if (source[j--] != target[k--]) {
i--;
continue startSearchForLastChar;
}
}
return start - sourceOffset + 1;
}
}
【g】substring()截取字符串
//返回指定索引处的字符开头到字符串的末尾的子串
public String substring(int beginIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
//计算开始索引与字符串长度的差值
int subLen = value.length - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
//如果长度一样,说明就是字符串本身,返回this
//如果长度不一样,重新new一个新的字符串对象返回
return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}
//返回开始索引到结束索引的子串
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
//计算需要截取的子串的长度
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
public CharSequence subSequence(int beginIndex, int endIndex) {
return this.substring(beginIndex, endIndex);
}
【h】concat()字符串拼接
//将指定的字符串连接到此字符串的末尾
// "cares".concat("s") returns "caress"
// "to".concat("get").concat("her") returns "together"
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
//实际调用System.arraycopy
str.getChars(buf, len);
return new String(buf, true);
}
【i】replace()、replaceAll()
//使用新字符替换字符串中指定的字符
Examples:
* <blockquote><pre>
* "mesquite in your cellar".replace('e', 'o')
* returns "mosquito in your collar"
* "the war of baronets".replace('r', 'y')
* returns "the way of bayonets"
* "sparring with a purple porpoise".replace('p', 't')
* returns "starring with a turtle tortoise"
* "JonL".replace('q', 'x') returns "JonL" (no change)
public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
int len = value.length;
int i = -1;
char[] val = value; /* avoid getfield opcode */
while (++i < len) {
if (val[i] == oldChar) {
break;
}
}
if (i < len) {
char buf[] = new char[len];
for (int j = 0; j < i; j++) {
buf[j] = val[j];
}
while (i < len) {
char c = val[i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(buf, true);
}
}
return this;
}
//正则匹配
public boolean matches(String regex) {
return Pattern.matches(regex, this);
}
//实际上调用下面的代码:
public static boolean matches(String regex, CharSequence input) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
return m.matches();
}
//判断字符串是否包含指定的字符
public boolean contains(CharSequence s) {
//利用indexOf函数,如果找得到即indexOf函数返回值大于-1则返回true,找不到返回false
return indexOf(s.toString()) > -1;
}
//替换此字符串中与给定的正则表达式匹配的字符为replacement
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
【j】split()切割函数、join()拼接字符串
扫描二维码关注公众号,回复:
8656564 查看本文章
//使用指定的分隔符切割字符串
public String[] split(String regex, int limit) {
/* fastpath if the regex is a
(1)one-char String and this character is not one of the
RegEx's meta characters ".$|()[{^?*+\\", or
(2)two-char String and the first char is the backslash and
the second is not the ascii digit or ascii letter.
*/
char ch = 0;
if (((regex.value.length == 1 &&
".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
(regex.length() == 2 &&
regex.charAt(0) == '\\' &&
(((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
((ch-'a')|('z'-ch)) < 0 &&
((ch-'A')|('Z'-ch)) < 0)) &&
(ch < Character.MIN_HIGH_SURROGATE ||
ch > Character.MAX_LOW_SURROGATE))
{
int off = 0;
int next = 0;
boolean limited = limit > 0;
//使用ArrayList存储切割之后的所有字符
ArrayList<String> list = new ArrayList<>();
while ((next = indexOf(ch, off)) != -1) {
if (!limited || list.size() < limit - 1) {
list.add(substring(off, next));
off = next + 1;
} else { // last one
//assert (list.size() == limit - 1);
list.add(substring(off, value.length));
off = value.length;
break;
}
}
// If no match was found, return this
if (off == 0)
return new String[]{this};
// Add remaining segment
if (!limited || list.size() < limit)
list.add(substring(off, value.length));
// Construct result
int resultSize = list.size();
if (limit == 0) {
while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
resultSize--;
}
}
String[] result = new String[resultSize];
return list.subList(0, resultSize).toArray(result);
}
//直接使用正则表达式进行切割
return Pattern.compile(regex).split(this, limit);
}
public String[] split(String regex) {
return split(regex, 0);
}
//使用指定的分隔符拼接字符串,采用可变参数进行接收多个字符串对象
// String message = String.join("-", "Java", "is", "cool");
// message returned is: "Java-is-cool"
public static String join(CharSequence delimiter, CharSequence... elements) {
Objects.requireNonNull(delimiter);
Objects.requireNonNull(elements);
// Number of elements not likely worth Arrays.stream overhead.
//基于StringJoiner 实现拼接,通过封装StringBuilder实现
StringJoiner joiner = new StringJoiner(delimiter);
for (CharSequence cs: elements) {
joiner.add(cs);
}
return joiner.toString();
}
public static String join(CharSequence delimiter,
Iterable<? extends CharSequence> elements) {
Objects.requireNonNull(delimiter);
Objects.requireNonNull(elements);
StringJoiner joiner = new StringJoiner(delimiter);
for (CharSequence cs: elements) {
joiner.add(cs);
}
return joiner.toString();
}
【k】转换大小写toLowerCase()、toUpperCase()
//转换大小写
public String toLowerCase(Locale locale) {
if (locale == null) {
throw new NullPointerException();
}
int firstUpper;
final int len = value.length;
/* Now check if there are any characters that need to be changed. */
scan: {
for (firstUpper = 0 ; firstUpper < len; ) {
char c = value[firstUpper];
if ((c >= Character.MIN_HIGH_SURROGATE)
&& (c <= Character.MAX_HIGH_SURROGATE)) {
int supplChar = codePointAt(firstUpper);
if (supplChar != Character.toLowerCase(supplChar)) {
break scan;
}
firstUpper += Character.charCount(supplChar);
} else {
if (c != Character.toLowerCase(c)) {
break scan;
}
firstUpper++;
}
}
return this;
}
char[] result = new char[len];
int resultOffset = 0; /* result may grow, so i+resultOffset
* is the write location in result */
/* Just copy the first few lowerCase characters. */
//只需复制前几个小写字母
System.arraycopy(value, 0, result, 0, firstUpper);
String lang = locale.getLanguage();
boolean localeDependent =
(lang == "tr" || lang == "az" || lang == "lt");
char[] lowerCharArray;
int lowerChar;
int srcChar;
int srcCount;
for (int i = firstUpper; i < len; i += srcCount) {
srcChar = (int)value[i];
if ((char)srcChar >= Character.MIN_HIGH_SURROGATE
&& (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
srcChar = codePointAt(i);
srcCount = Character.charCount(srcChar);
} else {
srcCount = 1;
}
if (localeDependent ||
srcChar == '\u03A3' || // GREEK CAPITAL LETTER SIGMA
srcChar == '\u0130') { // LATIN CAPITAL LETTER I WITH DOT ABOVE
lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
} else {
lowerChar = Character.toLowerCase(srcChar);
}
if ((lowerChar == Character.ERROR)
|| (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
if (lowerChar == Character.ERROR) {
lowerCharArray =
ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
} else if (srcCount == 2) {
resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
continue;
} else {
lowerCharArray = Character.toChars(lowerChar);
}
/* Grow result if needed */
int mapLen = lowerCharArray.length;
if (mapLen > srcCount) {
char[] result2 = new char[result.length + mapLen - srcCount];
System.arraycopy(result, 0, result2, 0, i + resultOffset);
result = result2;
}
for (int x = 0; x < mapLen; ++x) {
result[i + resultOffset + x] = lowerCharArray[x];
}
resultOffset += (mapLen - srcCount);
} else {
result[i + resultOffset] = (char)lowerChar;
}
}
return new String(result, 0, len + resultOffset);
}
public String toLowerCase() {
return toLowerCase(Locale.getDefault());
}
public String toUpperCase(Locale locale) {
if (locale == null) {
throw new NullPointerException();
}
int firstLower;
final int len = value.length;
/* Now check if there are any characters that need to be changed. */
scan: {
for (firstLower = 0 ; firstLower < len; ) {
int c = (int)value[firstLower];
int srcCount;
if ((c >= Character.MIN_HIGH_SURROGATE)
&& (c <= Character.MAX_HIGH_SURROGATE)) {
c = codePointAt(firstLower);
srcCount = Character.charCount(c);
} else {
srcCount = 1;
}
int upperCaseChar = Character.toUpperCaseEx(c);
if ((upperCaseChar == Character.ERROR)
|| (c != upperCaseChar)) {
break scan;
}
firstLower += srcCount;
}
return this;
}
/* result may grow, so i+resultOffset is the write location in result */
int resultOffset = 0;
char[] result = new char[len]; /* may grow */
/* Just copy the first few upperCase characters. */
System.arraycopy(value, 0, result, 0, firstLower);
String lang = locale.getLanguage();
boolean localeDependent =
(lang == "tr" || lang == "az" || lang == "lt");
char[] upperCharArray;
int upperChar;
int srcChar;
int srcCount;
for (int i = firstLower; i < len; i += srcCount) {
srcChar = (int)value[i];
if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
(char)srcChar <= Character.MAX_HIGH_SURROGATE) {
srcChar = codePointAt(i);
srcCount = Character.charCount(srcChar);
} else {
srcCount = 1;
}
if (localeDependent) {
upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
} else {
upperChar = Character.toUpperCaseEx(srcChar);
}
if ((upperChar == Character.ERROR)
|| (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
if (upperChar == Character.ERROR) {
if (localeDependent) {
upperCharArray =
ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
} else {
upperCharArray = Character.toUpperCaseCharArray(srcChar);
}
} else if (srcCount == 2) {
resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
continue;
} else {
upperCharArray = Character.toChars(upperChar);
}
/* Grow result if needed */
int mapLen = upperCharArray.length;
if (mapLen > srcCount) {
char[] result2 = new char[result.length + mapLen - srcCount];
System.arraycopy(result, 0, result2, 0, i + resultOffset);
result = result2;
}
for (int x = 0; x < mapLen; ++x) {
result[i + resultOffset + x] = upperCharArray[x];
}
resultOffset += (mapLen - srcCount);
} else {
result[i + resultOffset] = (char)upperChar;
}
}
return new String(result, 0, len + resultOffset);
}
public String toUpperCase() {
return toUpperCase(Locale.getDefault());
}
【l】trim()去除字符串前后空格
//去除字符串前后的空格
public String trim() {
int len = value.length;
int st = 0;
char[] val = value; /* avoid getfield opcode */
//从头部开始循环,直到碰到不为空字符,此时记录开始索引st
while ((st < len) && (val[st] <= ' ')) {
st++;
}
//从尾部开始循环,直到碰到不为空字符,此时记录结束索引len
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
//截取字符串substring(st, len)
return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}
【m】toString()
//这个对象(它已经是一个字符串了!)本身是返回的。
public String toString() {
return this;
}
//将这个字符串转换成一个新的字符数组。
public char[] toCharArray() {
// Cannot use Arrays.copyOf because of class initialization order issues
char result[] = new char[value.length];
//不能使用数组。由于类初始化顺序问题
//所以使用 System.arraycopy进行数组拷贝
System.arraycopy(value, 0, result, 0, value.length);
return result;
}
【n】valueOf():将对象转换为字符串
//将对象转换为字符串对象
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
//将字符数组转换为字符串对象
public static String valueOf(char data[]) {
return new String(data);
}
public static String valueOf(char data[], int offset, int count) {
return new String(data, offset, count);
}
//将boolean类型的对象转换为字符串类型的"true"或"false"
public static String valueOf(boolean b) {
return b ? "true" : "false";
}
//将字符转换为字符串对象
public static String valueOf(char c) {
//只有一个元素的字符数组,然后通过String构造方法创建新对象
char data[] = {c};
return new String(data, true);
}
//将整形对象转换为字符串
public static String valueOf(int i) {
return Integer.toString(i);
}
//将long类型对象转换为字符串
public static String valueOf(long l) {
return Long.toString(l);
}
//将float类型对象转换为字符串
public static String valueOf(f) {
return Float.toString(f);
}
//将double类型对象转换为字符串
public static String valueOf(double d) {
return Double.toString(d);
}
【o】intern():与字符串常量池相关的方法
//该方法是native本地方法,由系统动态库实现,与字符串常量池相关
public native String intern();