public final class String
implements java.io.Serializable, Comparable, CharSequence {
private final char value[];
private int hash; // Default to 0
- String类用final修饰,不能被继承,其本质是一个用final修饰的char型数组。这个数组是private的,对外不可见,String类没有提供修改该数组的方法,所以String类的对象(字符串)的值是不可以修改的,修改的是对象的引用。
public String() {
this.value = "".value;
}
//-----------------------------------
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
//--------------------------------------
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
//Arrays类中的copyOf()方法
public static char[] copyOf(char[] original, int newLength) {
char[] copy = new char[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
//System类里的arraycopy()本地方法
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
//-----------------------------------------------------------
//分配新的{@code String},该字符串包含字符数组参数的子数组中的字符。{@code offset}参数是
//子数组第一个字符的索引和{@code 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);
}
this.value = Arrays.copyOfRange(value, offset, offset+count);
}
//从offset开始截取count长度的字符串
//------------------------------------------------------------------------
//StringBUffer转String
public String(StringBuffer buffer) {
synchronized(buffer) {
this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
}
}
//--------------------------------------------------------------------------
public String(StringBuilder builder) {
this.value = Arrays.copyOf(builder.getValue(), builder.length());
}
- 如何理解offset or count might be near -1>>>1
- -1>>>1代表什么,他其实就是Integer.MAX_VALUE,即2147483647,因为整型-1的计算机内部表示是整型1的计算机内部表示取反加一,整型1的计算机内部是00000000 00000000 00000000 00000001,取反加一后得到11111111 11111111 11111111 11111111,>>>代表无符号右移,右移之后高位补0,右移一位之后得到01111111 11111111 11111111 11111111,最高位是符号位,0代表正数,所以最终-1>>>1表示2147483647。
- offsett或者count可能接近这个值,接近这个值之后可能会发生什么,也就是会overflow了
public int length() {
return value.length;
}
- 返回value数组的长度
public boolean isEmpty() {
return value.length == 0;
}
- 判断value数组的长度是否等于0,返回true或false
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
- 先判断索引值是否有效,无效抛出异常,有效返回value[index]
public boolean equals(Object anObject) {
//先判断引用是否相同,引用即地址相同则为同一对象
if (this == anObject) {
return true;
}
//判断anObject是否是String的实例
//instanceof是Java 的保留关键字。它的作用是测试它左边的对象是否是它右边的类的实例,返回boolean的数据类型
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
//判断两个字符串的长度是否一致
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
//最后挨个字符进行比较
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
-
instanceof是Java 的保留关键字。它的作用是测试它左边的对象是否是它右边的类的实例,返回boolean的数据类型
-
如果是同一个引用,则返回true;两个字符串的长度若一致则逐个字符进行比较。
public boolean equalsIgnoreCase(String anotherString) {
return (this == anotherString) ? true//判断要比较的两个字符串是否是同一引用
: (anotherString != null)//比较的字符串是否是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, 或 len 可能接近 -1>>>1.
if ((ooffset < 0) || (toffset < 0)//两个要比较的字符串的子字符串的起始索引,小于0则越界
//起始索引加比较长度是否大于字符串的长度
//直接使用(起始索引+比较长度>字符串长度)可能会overflow,因为toffset,ooffset,或len可能接近-1>>>1
|| (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) {
//如果字符不匹配,但大小写可能会被忽略,
//尝试将两个字符都转换为大写.
//如果结果匹配,则应该继续进行比较循环.
char u1 = Character.toUpperCase(c1);
char u2 = Character.toUpperCase(c2);
if (u1 == u2) {
continue;
}
// 不幸的是,对格鲁吉亚字母的大写转换不能正常工作,它有关于大小写转换的奇怪规则。
// 所以我们需要在退出前做最后一次检查
if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
continue;
}
}
return false;
}
return true;
}
大小比较 compareTo(String anotherString)
//对字符逐个进行比较
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;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
不区分大小写的大小比较 compareToIgnoreCase(String str)
public int compareToIgnoreCase(String str) {
return CASE_INSENSITIVE_ORDER.compare(this, str);
}
//静态内部类
public static final Comparator CASE_INSENSITIVE_ORDER
= new CaseInsensitiveComparator();
private static class CaseInsensitiveComparator
implements Comparator, 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;
}
是否以指定前缀开头 startsWith(String prefix, int toffset)
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;
}
- 从toffset位置开始比较
public boolean startsWith(String prefix) {
return startsWith(prefix, 0);
}
- 从0开始比较
public boolean endsWith(String suffix) {
//开始索引为字符串长度减去后缀长度
return startsWith(suffix, value.length - suffix.value.length);
}
- 调用startswith方法,从value.length - suffix.value.length开始比较
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;
}
获取首次出现指定字符的索引 indexOf(int ch)
//返回指定字符在该字符串中第一次出现的索引。
public int indexOf(int ch) {
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) {
// Note: fromIndex might be near -1>>>1.
return -1;
}
//MIN_SUPPLEMENTARY_CODE_POINT:最小补充码点 Unicode编码:0x010000
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// 在这里处理大多数情况(ch是BMP码点或负值(无效码点))
final char[] value = this.value;
for (int i = fromIndex; i < max; i++) {
if (value[i] == ch) {
return i;
}
}
return -1;
} else {
return indexOfSupplementary(ch, fromIndex);
}
}
//
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;
}
- 从前往后判断,直到找到第一个匹配的字符,返回数组下标。其他情况返回-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);
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;
}
- 从后往前判断,直到找到第一个匹配的字符,返回数组下标;否则返回-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);
}
//由String和StringBuffer共享进行搜索的代码。源是要搜索的字符数组,目标是要搜索的字符串
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);
}
//起始索引小于0,默认等于0
if (fromIndex < 0) {
fromIndex = 0;
}
//子字符串长度等于0,返回fromIndex
if (targetCount == 0) {
return fromIndex;
}
char first = target[targetOffset];
int max = sourceOffset + (sourceCount - targetCount);
//sourceOffset、sourceOffset + fromIndex、max会有越界问题,返回-1
for (int i = sourceOffset + fromIndex; i <= max; i++) {
if (source[i] != first) {
while (++i <= max && source[i] != first);
}
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) {
return i - sourceOffset;
}
}
}
return -1;
}
截取字符串
//越界抛异常 StringIndexOutOfBoundsException
public String substring(int beginIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
int subLen = value.length - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);
}
- 从指定开始位置截取,判断beginIndex是否合法;返回this或new String(value, beginIndex, subLen)
//越界抛异常 StringIndexOutOfBoundsException
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);
}
//根据指定开始位置和结束位置截取,判断beginIndex和endIndex是否合法;
//返回this或new String(value, beginIndex, subLen)
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
字符串拼接
//将指定的字符串连接到该字符串的末尾。
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;、
//调用Arrays.copyOf方法
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}
//从dstBegin开始,将该字符串中的字符复制到dst中。
void getChars(char dst[], int dstBegin) {
System.arraycopy(value, 0, dst, dstBegin, value.length);
}
- 也可使用运算符+拼接两个字符串
//返回替换所有匹配项后得到的字符串
public String replace(char oldChar, char newChar) {
//判断新旧字符是否相等
if (oldChar != newChar) {
int len = value.length;
int i = -1;
char[] val = value;
//选遍历一次找到旧字符
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;
}
- 替换所有匹配的字符,先找到第一个匹配的字符,获取索引,先复制前面没有该字符的部分,然后从该索引开始用while循环替换所有匹配的字符,最后返回new String(buf, true);否则返回原字符串。
//替换该字符串中与给定匹配的第一个子字符串
public String replaceFirst(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
}
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
拆分字符串
//在给定的匹配项周围拆分此字符串
public String[] split(String regex, int limit) {
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 list = new ArrayList<>();
//while循环判断未遍历字符中是否存在目标字符
while ((next = indexOf(ch, off)) != -1) {
//若不限制个数或者已满足指定个数则为true
if (!limited || list.size() < limit - 1) {
//调用substring方法
list.add(substring(off, next));
//起始索引加一,继续循环
off = next + 1;
} else { // 最后一个
//必定 (list.size() == limit - 1);
list.add(substring(off, value.length));
off = value.length;
//跳出循环
break;
}
}
// 如果没有找到匹配,则返回new String[]{this}
if (off == 0)
return new String[]{this};
//添加剩余的部分
if (!limited || list.size() < limit)
list.add(substring(off, value.length));
//构建结果
int resultSize = list.size();
if (limit == 0) {
//获取实际长度
while (resultSize > 0 && list.get(resultSize - 1).length() == 0) {
resultSize--;
}
}
String[] result = new String[resultSize];
//截取list并转为String[]返回
return list.subList(0, resultSize).toArray(result);
}
//如果regex是正则表达式
return Pattern.compile(regex).split(this, limit);
}
//因为ch = regex.charAt(0)或者ch = regex.charAt(1),所以参数regex只能是单个字符的字符串或者是需要转义的字符串;
//若是多个字符的字符串,则需要使用正则表达式
public String[] split(String regex) {
return split(regex, 0);
}
类型转换
转char[]
public char[] toCharArray() {
// 由于类初始化顺序问题,无法使用Arrays.copyOf
char result[] = new char[value.length];
System.arraycopy(value, 0, result, 0, value.length);
return result;
}
Object转String
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
char[]转String
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);
}
//
public static String copyValueOf(char data[], int offset, int count) {
return new String(data, offset, count);
}
//
public static String copyValueOf(char data[]) {
return new String(data);
}
boolean转String
public static String valueOf(boolean b) {
return b ? "true" : "false";
}
char转String
public static String valueOf(char c) {
char data[] = {c};//先转字符数组
return new String(data, true);//传入字符数组重新构造
}
int转String
public static String valueOf(int i) {
return Integer.toString(i);
}
long转String
public static String valueOf(long l) {
return Long.toString(l);
}
float转String
public static String valueOf(float f) {
return Float.toString(f);
}
double转String
public static String valueOf(double d) {
return Double.toString(d);
}



