package java.lang;
import java.io.ObjectStreamField;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Formatter;
import java.util.Locale;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* final 修饰的类不可被继承也不可变
* java.io.Serializable 仅用于标识该类可序列化的意思
* Comparable<String> 这个接口只有一个compareTo(T 0)接口,用于对两个实例化对象比较大小,
* 实现了这个接口就意味着该类支持排序
* CharSequence 这个接口是一个只读的字符序列。包括length(), charAt(int index),
* subSequence(int start, int end)这几个API接口,值得一提的是,
* StringBuffer和StringBuild也是实现了、该接口
*/
public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
/**
* 用于存储当前字符串中每个char字符,即当使用String str = "abc";的时候,
* 本质上,"abc"是存储在一个char类型的数组中的 {'a', 'b', 'c'}
* 且被final修饰,一旦创建则不可修改,虽然该类中提供了很多字符串操作和修改的方法,
* 但每次修改底层都是创建了一个新的字符串
* */
private final char value[];
/**
* 而hash是String实例化的hashcode的一个缓存。因为String经常被用于比较,
* 比如在HashMap中,如果每次进行比较都重新计算hashcode的值的话,
* 那无疑是比较麻烦的,而保存一个hashcode的缓存无疑能优化这样的操作。
* 默认是0
* */
private int hash;
/**
* serialVersionUID 是一个序列化版本号,Java 通过这个 UID 来判定反序列化时的字节流与本地类的一致性,
* 如果相同则认为一致,可以进行反序列化,如果不同就会抛出异常,
* 很多工具默认给的都是 -1L,也是为了确保可以进行反序列化
* */
private static final long serialVersionUID = -6849794470754667710L;
/**
* 静态字段名serialPersistentFields 用于指定哪些字段需要被默认序列化。
* transient 用于指定哪个字段不被默认序列化,
* 如果同时定义了 serialPersistentFields 与 transient,transient 会被忽略,
* 但是数组的长度为什么是0????
*/
private static final ObjectStreamField[] serialPersistentFields = new ObjectStreamField[0];
/**
* String的无参数构造方法,默认是 "" 空字符串
*/
public String() {
this.value = "".value;
}
/**
* String带参数构造方法
*/
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
/**
* 为什么使用Arrays.copyOf?而不使用this.value = value
* 传递的value[]参数是可变的,如果是使用this.value = value String将失去不可变性
* 而Arrays.copyof采用浅复制,保留了this.value的不可变性
* @param value
*/
public String(char value[]) { this.value = Arrays.copyOf(value, value.length); }
/**
* 将char数组中指定开始索引和个数范围内的元素构建成新字符串
* value char数组
* 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);
}
this.value = Arrays.copyOfRange(value, offset, offset+count);
}
/**
* 将int数组中指定开始索引和范围的int数值转成char并构建成新的字符串
*/
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;
}
@Deprecated
public String(byte ascii[], int hibyte, int offset, int count) {
checkBounds(ascii, offset, count);
char value[] = new char[count];
if (hibyte == 0) {
for (int i = count; i-- > 0;) {
value[i] = (char)(ascii[i + offset] & 0xff);
}
} else {
hibyte <<= 8;
for (int i = count; i-- > 0;) {
value[i] = (char)(hibyte | (ascii[i + offset] & 0xff));
}
}
this.value = value;
}
@Deprecated
public String(byte ascii[], int hibyte) {
this(ascii, hibyte, 0, ascii.length);
}
/* Common private utility method used to bounds check the byte array
* and requested offset & length values used by the String(byte[],..)
* constructors.
*/
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);
this.value = StringCoding.decode(charsetName, bytes, offset, length);
}
/**
* 将指定编码格式、开始索引和个数范围的字节数组构建新的字符串
* bytes 字节数组
* offset 起始索引
* length 长度
* 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);
}
/**
* 使用指定的编码格式,将字节数组构建新的字符串
* bytes 字节数组
* charsetName 编码格式名
*/
public String(byte bytes[], String charsetName) throws UnsupportedEncodingException {
this(bytes, 0, bytes.length, charsetName);
}
/**
* 对指定的字节数组使用指定的charset编码格式进行解码,构造了一个新的 String。
*/
public String(byte bytes[], Charset charset) {
this(bytes, 0, bytes.length, charset);
}
/**
* 字节数组构建新的字符串
* bytes 字节数组
* offset 开始索引
* length 个数
*/
public String(byte bytes[], int offset, int length) {
checkBounds(bytes, offset, length);
this.value = StringCoding.decode(bytes, offset, length);
}
/**
* 使用平台的默认字符集解码指定的字节数组构造了一个新的 String。
*/
public String(byte bytes[]) {
this(bytes, 0, bytes.length);
}
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());
}
/*
* Package private constructor which shares value array for speed.
* this constructor is always expected to be called with share==true.
* a separate constructor is needed because we already have a public
* String(char[]) constructor that makes a copy of the given char[].
*
* 从注释可以看出,现在只支持 share 为 true,并且这样构造的字符串直接和字符数组共享,性能提高了。
* 这个方法之所以没有设为protected是因为一旦公开就破坏了字符串的不可变性,可以直接修改字符数组去修改字符串了。
*/
String(char[] value, boolean share) {
// assert share : "unshared not supported";
this.value = value;
}
/**
* 获取字符串的长度
*/
public int length() {
return value.length;
}
/**
* 根据字符串的长度,判断是否为""空字符串
*/
public boolean isEmpty() {
return value.length == 0;
}
/**
* 获取指定索引的char字符,索引从0开始
* 示例:
* "abc".charAt(0); //a
*/
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
//索引值小于0或大于等于字符串的长度,则抛出索引越界异常
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
/**
* 返回指定索引的Unicode代码点的int值
* 示例:
* "abc".codePointAt(0); //返回a的Unicode的值 97
* String s = new String("\u1D56".getBytes(), "utf-8"); //将\u1D56字节数组用utf-8的编码格式进行解码,构建一个String,
* System.err.println(s); // ᵖ
* System.err.println(s.length()); // 1
* System.err.println(s.charAt(0)); // ᵖ
* System.err.println(s.codePointAt(0)); // 7510
* System.err.println(s.codePointBefore(1)); // 7510
* System.err.println(s.codePointCount(0, s.length())); // 1
*/
public int codePointAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return Character.codePointAtImpl(value, index, value.length);
}
/**
* 返回指定索引前一个Unicode代码点的int值
* 示例:
* "abc".codePointBefore(1); //返回a的Unicode的值 97
*/
public int codePointBefore(int index) {
//指定的索引 -1
int i = index - 1;
if ((i < 0) || (i >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return Character.codePointBeforeImpl(value, index, 0);
}
/**
* 指定索引开始和结束的范围内Unicode代码点的个数(索引范围含头不含尾)
*/
public int codePointCount(int beginIndex, int endIndex) {
if (beginIndex < 0 || endIndex > value.length || beginIndex > endIndex) {
throw new IndexOutOfBoundsException();
}
return Character.codePointCountImpl(value, beginIndex, endIndex - beginIndex);
}
/**
* Returns the index within this {@code String} that is
* offset from the given {@code index} by
* {@code codePointOffset} code points. Unpaired surrogates
* within the text range given by {@code index} and
* {@code codePointOffset} count as one code point each.
*
* @param index the index to be offset
* @param codePointOffset the offset in code points
* @return the index within this {@code String}
* @exception IndexOutOfBoundsException if {@code index}
* is negative or larger then the length of this
* {@code String}, or if {@code codePointOffset} is positive
* and the substring starting with {@code index} has fewer
* than {@code codePointOffset} code points,
* or if {@code codePointOffset} is negative and the substring
* before {@code index} has fewer than the absolute value
* of {@code codePointOffset} code points.
* @since 1.5
*/
public int offsetByCodePoints(int index, int codePointOffset) {
if (index < 0 || index > value.length) {
throw new IndexOutOfBoundsException();
}
return Character.offsetByCodePointsImpl(value, 0, value.length, index, codePointOffset);
}
/**
* 将当前字符串的字符复制到dst目标char数组中
* dst -- 目标数组。
* dstBegin -- 目标数组中的起始偏移量
*/
void getChars(char dst[], int dstBegin) {
System.arraycopy(value, 0, dst, dstBegin, value.length);
}
/**
* srcBegin -- 字符串中要复制的第一个字符的索引。
* srcEnd -- 字符串中要复制的最后一个字符之后的索引。
* dst -- 目标数组。
* dstBegin -- 目标数组中的起始偏移量。
*/
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
if (srcBegin < 0) {
throw new StringIndexOutOfBoundsException(srcBegin);
}
if (srcEnd > value.length) {
throw new StringIndexOutOfBoundsException(srcEnd);
}
if (srcBegin > srcEnd) {
throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
}
System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
}
@Deprecated
public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
if (srcBegin < 0) {
throw new StringIndexOutOfBoundsException(srcBegin);
}
if (srcEnd > value.length) {
throw new StringIndexOutOfBoundsException(srcEnd);
}
if (srcBegin > srcEnd) {
throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
}
Objects.requireNonNull(dst);
int j = dstBegin;
int n = srcEnd;
int i = srcBegin;
char[] val = value; /* avoid getfield opcode */
while (i < n) {
dst[j++] = (byte)val[i++];
}
}
/**
* 使用指定的字符集编码进行解码,获取当前字符串的字节数组
*/
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);
}
/**
* 这段代码在不同的平台上运行得到结果是不一样的。由于我们没有指定编码方式,
* 所以在该方法对字符串进行编码的时候就会使用系统的默认编码方式,
* 比如在中文操作系统中可能会使用GBK或者GB2312进行编码,
* 在英文操作系统中有可能使用iso-8859-1进行编码。这样写出来的代码就和机器环境有很强的关联性了,
* 所以,为了避免不必要的麻烦,我们要指定编码方式。
*/
public byte[] getBytes() {
return StringCoding.encode(value, 0, value.length);
}
/**
* String重写了Object的equals方法
*/
public boolean equals(Object anObject) {
//先判断两个对象的地址值是否相同
if (this == anObject) {
return true;
}
//判断传递的参数是否是字符串类型
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;
//再分别比较字符串中的char数组的每一个char都要相等才返回true
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
/**
* 比较字符串的内容是否相同,区分大小写
*/
public boolean contentEquals(StringBuffer sb) {
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
if (cs instanceof AbstractStringBuilder) {
if (cs instanceof StringBuffer) {
// StringBuffer为线程安全的类型,所以当比较类型为StringBuffer类型时
// 使用同步代码块,用cs当作锁对象进行比较
synchronized(cs) {
return nonSyncContentEquals((AbstractStringBuilder)cs);
}
} else {
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 int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
//获取2个字符串最小的长度
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];
//循环遍历2个字符串中的char数组,如果不一样则返回两个char的差值
if (c1 != c2) {
return c1 - c2;
}
k++;
}
//如果字符串一样或者最小长度<=0则返回2个字符串的长度差值
return len1 - len2;
}
/**
* 静态内部类
* 静态成员是一个实现了 Comparator 想接口的类的实例,而实现这个类的作用是比较两个忽略大小写的 String 的大小
*
* String 为什么要对Comparable和Comparator都实现一遍呢?
* Comparable 是类的内部实现,一个类能且只能实现一次,而 Comparator 则是作为String的内部对Comparator进行了外部实现,
* 可以通过不改变类本身的情况下,为类增加更多的排序功能。
*/
public static final Comparator<String> CASE_INSENSITIVE_ORDER = new CaseInsensitiveComparator();
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; }
}
/**
* 忽略大小写比较两个字符串的差值,使用的是静态内部类的实现Comparator的compare(String s1, String s2)方法
*/
public int compareToIgnoreCase(String str) {
return CASE_INSENSITIVE_ORDER.compare(this, str);
}
/**
* 当前字符串从指定索引位置开始,与其他字符串指定为开始,在指定len长度中的char是否相同
*/
public boolean regionMatches(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) {
//先取ta[to]的值,然后to再 + 1
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
}
/**
* 当前字符串从指定索引位置开始,与其他字符串指定为开始,在指定len长度中的char是否相同
* ignoreCase 是否忽略大小写进行比较
*/
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;
}
/**
* 判断当前字符串从指定索引开始是否以prefix开头
*/
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);
}
/**
* 算法:s[0]*31^(n-1) + s[1]*31^(n-2) + … + s[n-1]
* s[i]表示字符串的第i个字符,n表示字符串的长度,^表示取幂。
*/
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;
}
/**
* 从索引0开始,获取字符串中第一个char的int值与参数相等的索引
*/
public int indexOf(int ch) {
return indexOf(ch, 0);
}
/**
* ch Unicode代码点
* fromIndex 起始位置索引
*/
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;
}
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;
for (int i = fromIndex; i < max; i++) {
if (value[i] == ch) {
return i;
}
}
return -1;
} else {
return indexOfSupplementary(ch, fromIndex);
}
}
/**
* Handles (rare) calls of indexOf with a supplementary character.
*/
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;
}
/**
* 从字符串的最后开始,获取第一个与ch相等的char字符的索引
*/
public int lastIndexOf(int ch) {
return lastIndexOf(ch, value.length - 1);
}
/**
* 从指定为向前,获取第一个与ch相等的char字符的索引
*/
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);
}
}
/**
* Handles (rare) calls of lastIndexOf with a supplementary character.
*/
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;
}
/**
* str在当前字符串第一次出现的索引位置
*/
public int indexOf(String str) {
return indexOf(str, 0);
}
/**
* str 要查找的字符串
* fromIndex 起始的索引
*/
public int indexOf(String str, int fromIndex) {
return indexOf(value, 0, value.length,
str.value, 0, str.value.length, fromIndex);
}
/**
* Code shared by String and AbstractStringBuilder to do searches. The
* source is the character array being searched, and the target
* is the string being searched for.
*
* @param source the characters being searched.
* @param sourceOffset offset of the source string.
* @param sourceCount count of the source string.
* @param target the characters being searched for.
* @param fromIndex the index to begin searching from.
*/
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);
}
/**
* Code shared by String and StringBuffer to do searches. The
* source is the character array being searched, and the target
* is the string being searched for.
*
* @param source the characters being searched.
* @param sourceOffset offset of the source string.
* @param sourceCount count of the source string.
* @param target the characters being searched for.
* @param targetOffset offset of the target string.
* @param targetCount count of the target string.
* @param fromIndex the index to begin searching from.
*/
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;
}
/**
* 从当前字符的最后开始往前查找str的索引位置
*/
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;
}
}
/**
* 截取开始索引到字符串的最后的字符串
* Examples:
* <blockquote><pre>
* "unhappy".substring(2) returns "happy"
* "Harbison".substring(3) returns "bison"
* "emptiness".substring(9) returns "" (an empty string)
* </pre></blockquote>
*
* @param beginIndex the beginning index, inclusive.
* @return the specified substring.
* @exception IndexOutOfBoundsException if
* {@code beginIndex} is negative or larger than the
* length of this {@code String} object.
*/
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 开始索引
* endIndex 结束索引
* Examples:
* "hamburger".substring(4, 8) returns "urge"
* "smiles".substring(1, 5) returns "mile"
*/
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);
}
/**
* 与subString相比返回类型不一样,subString返回的是String,subSequence返回的是实现了
* CharSequence接口的类,也就是说使用subSequence得到的结果,只能使用CharSequence接口中的
* 方法。不过在String类中已经重写了subSequence,调用subSequence方法,可以直接下转为
* String对象
*/
public CharSequence subSequence(int beginIndex, int endIndex) {
return this.substring(beginIndex, endIndex);
}
/**
* 用newChar替换oldChar
*/
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 boolean contains(CharSequence s) {
return indexOf(s.toString()) > -1;
}
/**
* 使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。
*/
public String replaceFirst(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
}
/**
* 使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。
*/
public String replaceAll(String regex, String replacement) {
return Pattern.compile(regex).matcher(this).replaceAll(replacement);
}
/**
* 使用指定的replacement值替换target
*/
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
/**
* 根据给定正则表达式的匹配拆分此字符串。
* limit 参数通过控制分割次数从而影响分割结果
* 如果传入 n(n>0) 那么字符串最多被分割 n-1 次,分割得到数组长度最大是 n
* 如果 n = -1 将会以最大分割次数分割
* 如果 n = 0 将会以最大分割次数分割,但是分割结果会舍弃末位的空串
* 示例:
* "@2@3@".split("@",-1); //[ , 2, 3, ]
* "@2@3@".split("@",0); //[ , 2, 3]
* "@2@3@".split("@",2); //[ , 2@3@]
* "@2@3@".split("@",3); //[ , 2, 3@]
* "@2@3@".split("@",4); //[ , 2, 3, ]
* "@2@3@".split("@",5); //[ , 2, 3, ]
*/
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<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);
}
/**
* 根据给定正则表达式的匹配拆分此字符串。
* 示例:
* String str = "a,b,c";
* String[] arr = str.split(","); // {"a","b","c"}
*
*/
public String[] split(String regex) {
return split(regex, 0);
}
/**
* 将指定字符串连接到此字符串的结尾。
*/
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);
str.getChars(buf, len);
return new String(buf, true);
}
/**
* 将多个参数用delimiter进行拼接
* delimiter 拼接符
* elements 可变参数
*/
public static String join(CharSequence delimiter, CharSequence... elements) {
Objects.requireNonNull(delimiter);
Objects.requireNonNull(elements);
// Number of elements not likely worth Arrays.stream overhead.
StringJoiner joiner = new StringJoiner(delimiter);
for (CharSequence cs: elements) {
joiner.add(cs);
}
return joiner.toString();
}
/**
* elements可迭代参数
*/
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();
}
/**
* 按照给定的参数规则转换成小写。参数类型是Locale类型,它有以下值(列举了一部分)
* static Locale CANADA Useful constant for country.
* static Locale CANADA_FRENCH Useful constant for country.
* static Locale CHINA Useful constant for country.
* static Locale GERMANY Useful constant for country.
* static Locale FRANCE Useful constant for country.
* static Locale ITALY Useful constant for country.
* static Locale JAPAN Useful constant for country.
*/
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());
}
/**
* Converts all of the characters in this {@code String} to upper
* case using the rules of the given {@code Locale}. Case mapping is based
* on the Unicode Standard version specified by the {@link java.lang.Character Character}
* class. Since case mappings are not always 1:1 char mappings, the resulting
* {@code String} may be a different length than the original {@code String}.
* <p>
* Examples of locale-sensitive and 1:M case mappings are in the following table.
*
* <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
* <tr>
* <th>Language Code of Locale</th>
* <th>Lower Case</th>
* <th>Upper Case</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>tr (Turkish)</td>
* <td>\u0069</td>
* <td>\u0130</td>
* <td>small letter i -> capital letter I with dot above</td>
* </tr>
* <tr>
* <td>tr (Turkish)</td>
* <td>\u0131</td>
* <td>\u0049</td>
* <td>small letter dotless i -> capital letter I</td>
* </tr>
* <tr>
* <td>(all)</td>
* <td>\u00df</td>
* <td>\u0053 \u0053</td>
* <td>small letter sharp s -> two letters: SS</td>
* </tr>
* <tr>
* <td>(all)</td>
* <td>Fahrvergnügen</td>
* <td>FAHRVERGNÜGEN</td>
* <td></td>
* </tr>
* </table>
* @param locale use the case transformation rules for this locale
* @return the {@code String}, converted to uppercase.
* @see java.lang.String#toUpperCase()
* @see java.lang.String#toLowerCase()
* @see java.lang.String#toLowerCase(Locale)
* @since 1.1
*/
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());
}
/**
* 去除字符串两端的空格
*/
public String trim() {
int len = value.length;
int st = 0;
char[] val = value; /* avoid getfield opcode */
//获取从头开始连续空格的结束索引
while ((st < len) && (val[st] <= ' ')) {
st++;
}
//获取从结尾开始连续空格的开始索引
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
//根据获取的索引截取字符串
return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}
/**
* This object (which is already a string!) is itself returned.
*
* @return the string itself.
*/
public String toString() {
return this;
}
/**
* 将当前字符串转成char[]数组
*/
public char[] toCharArray() {
// Cannot use Arrays.copyOf because of class initialization order issues
char result[] = new char[value.length];
System.arraycopy(value, 0, result, 0, value.length);
return result;
}
/**
* 用于创建格式化的字符串以及连接多个字符串对象
* format:格式字符串
* args:格式字符串中由格式说明符引用的参数
* ==================== 常规转换符 =============================
* %b、%B 格式化为布尔类型 false
* %h、%H 格式化为散列码 A05A5198
* %s、%S 格式化为字符串类型 "abc"
* %c、%C 格式化为字符类型 'w'
* %d 格式化为十进制数 26
* %0 格式化为八进制整数 12
* %x、%X 格式化为十六进制整数 4b 1
* %e 格式化为用计算机科学计数法表示的十进制数 1.700000e+01
* %a 格式化为带有效位数和指数的十六进制浮点值 0X1.C000000000001P4
* %n 结果为特定于平台的行分隔符
* %% 结果为字面值%, %
*
* ================================ 常见的日期和时间转换符 ================================
* %te 一个月中的某一天(1〜31) 12
* %tb 指定语言环境的月份简称 Jan (英文)、一月(中文)
* %tB 指定语言环境的月份全称 February (英文)、二月(中文)
* %tA 指定语言环境的星期几全称 Monday (英文)、星期一(中文)
* %ta 指定语言环境的星期几简称 Mon (英文)、星期一(中文)
* %tc 包括全部日期和时间信息 星期三 十月 25 13:37:22 CST 2008
* %tY 4位年份 2008
* %tj 一年中的第几天(001〜366) 060
* %tm 月份 05
* %td 一个月中的第几天(01〜31) 07
* %ty 两位年份 08
*/
public static String format(String format, Object... args) {
return new Formatter().format(format, args).toString();
}
/**
* l : 格式化过程中要应用的语言环境。如果 l 为 null,则不进行本地化。
*/
public static String format(Locale l, String format, Object... args) {
return new Formatter(l).format(format, args).toString();
}
/**
* copyValueOf只能操作char数组进行构建新的字符串
* 但实现过程都是用的String的构造方法
*/
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);
}
/**
* 将不同数据类型转成字符串的表现形式
*/
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(boolean b) {
return b ? "true" : "false";
}
public static String valueOf(char c) { char data[] = {c}; return new String(data, true); }
public static String valueOf(int i) {
return Integer.toString(i);
}
public static String valueOf(long l) {
return Long.toString(l);
}
public static String valueOf(float f) {
return Float.toString(f);
}
public static String valueOf(double d) {
return Double.toString(d);
}
/**
* 从指定索引位置开始获取指定个数char字符,构建新的字符串
*/
public static String valueOf(char data[], int offset, int count) {
return new String(data, offset, count);
}
/**
* 这个方法的作用是如果常量池中存在当前字符串,就会直接返回当前字符串,如果常量池中没有此字符串,
* 会将此字符串放入常量池中后再返回。通过注释的介绍已经可以明白这个方法的作用了
* 示例:
* String s1 = "hello";
* String s2 = new String("hello");
* String s3 = s2.intern(); //从常量池中获取s2的实例,因为"hello"也就是s1已经存在,所以直接返回s1的引用
* System.out.println("s1 == s2: " + String.valueOf(s1 == s2)); //s2是new的对象,new关键字都是创建新的对象引用,所以false
* System.out.println("s1 == s3: " + String.valueOf(s1 == s3)); //true
*/
public native String intern();
}