JDK源码解析--String类
- equals(Object anObject)
- contentEquals(CharSequence cs)
- compareTo(String anotherString)
- startsWith(String prefix, int toffset)
- endsWith(String suffix)
- indexOf(int ch)
- indexOf(int ch, int fromIndex)
- indexOf(String str)
- indexOf(String str, int fromIndex)
- substring(int beginIndex, int endIndex)
- split(String regex, int limit)
- concat(String str)
- contains(CharSequence s)
- replace(char oldChar, char newChar)
equals(Object anObject)
equals方法相信大家都比较熟悉和了解了,string的equals方法主要用来比较String对象内容序列的异同,源码如下:
public boolean equals(Object anObject) {
// 判断地址是否相等,相等直接返回
if (this == anObject) {
return true;
}
// 判断是否是string类型
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length; //获取当前字符串的长度
// 判断当前字符串和传入的字符串的长度是否相等
if (n == anotherString.value.length) {
char v1[] = value; //获取当前字符串的char数组
char v2[] = anotherString.value; //获取传入的字符串char数组
int i = 0;
// 循环判断每一个字节是否相等有一位不相等就返回false
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
contentEquals(CharSequence cs)
contentEquals与equals方式差不多(唯一区别就是equals方法只能是string而这个方法只要是CharSequence子类都可以)如:StringBuffer,StringBuilder与string的比较
// 与equals方式差不多(唯一区别就是equals方法只能是string而这个方法只要是CharSequence子类都可以)
public boolean contentEquals(CharSequence cs) {
// Argument is a StringBuffer, StringBuilder
if (cs instanceof AbstractStringBuilder) {
if (cs instanceof StringBuffer) {
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;
}
compareTo(String anotherString)
它是先比较对应字符的大小(ASCII码顺序),如果第一个字符和参数的第一个字符不等,结束比较,返回他们之间的差值,如果第一个字符和参数的第一个字符相等,则以第二个字符和参数的第二个字符做比较,以此类推,直至比较的字符或被比较的字符有一方结束,源码如下:
public int compareTo(String anotherString) {
int len1 = value.length; //获取当前字符串长度
int len2 = anotherString.value.length; //获取传入字符串长度
int lim = Math.min(len1, len2); //比较两个大小取小
char v1[] = value; //获取当前字符串char数组
char v2[] = anotherString.value; //获取传入字符串char数组
int k = 0;
// 判断最小长度的数据的每一位字节是否与最大的长度的字节相等,如果不相等return不相等的长度
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
startsWith(String prefix, int toffset)
这个方法是用来判断从toffset开始,prefix与当前字符串是否相等
public boolean startsWith(String prefix, int toffset) {
char ta[] = value; //获取当前字符串char数组
int to = toffset; //查找索引
char pa[] = prefix.value; //传入数组char数组
int po = 0;
int pc = prefix.value.length; //传入数据长度
// 如果所有小于0 或者 索引大于当前字符串的长度减去要比较的的字符串长度大
if ((toffset < 0) || (toffset > value.length - pc)) {
return false;
}
// 从当前字符串char数组索引位置开始查找传入的字符串是否与之相等
while (--pc >= 0) {
if (ta[to++] != pa[po++]) {
return false;
}
}
return true;
}
endsWith(String suffix)
这个方法是用来判断当前字符的长度和传入字符串长度相减作为索引,来判断后面是否相等,如:判断文件后缀名等,源码如下:
public boolean endsWith(String suffix) {
return startsWith(suffix, value.length - suffix.value.length);
}
indexOf(int ch)
返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1
indexOf(int ch, int fromIndex)
返回从fromIndex开始在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1
indexOf(String str)
返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1
indexOf(String str, int fromIndex)
返回从fromIndex开始在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1
substring(int beginIndex, int endIndex)
截取从beginIndex到endIndex位置的字符串,源码如下:
public String substring(int beginIndex, int endIndex) {
// 开始位置大于0
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);
}
// 如果开始位置等于0并且结束位置等于当前字符串的长度返回自己本身,否则截取
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
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);
}
public static char[] copyOfRange(char[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
char[] copy = new char[newLength];
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
/**
* @param src 原数组
* @param srcPos 从元数据的起始位置开始
* @param dest 目标数组
* @param destPos 目标数组起始位置
* @param length 要copy的长度
*/
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
split(String regex, int limit)
根据正则表达式分割字符串,limit限定分割后的子字符串个数,超过数量限制的情况下前limit-1个子字符串正常分割,最后一个子字符串包含剩下所有字符
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;
/**
* 1:regex长度为1时,将regex赋给ch,判断ch是否在.$|()[{^?*+\\中
* 2:egex长度为2时,第一个字符为\\(要表示一个\需要用两个\\转义得到),第二个字符不在0-9,a-z,A-Z中
* 3:且不在Unicode编码的\uD800-\uDBFF之间
*/
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) {
// limit小于0或者list的大小小于limit减1,如果没有满足余下的字符串全部添加到list
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();
// 当limit为0时 从最后一个往前所有的空字符串""全部被清空
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);
}
concat(String str)
字符串拼接,源码如下:
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);
// 将传入的字符串加入buf
str.getChars(buf, len);
return new String(buf, true);
}
contains(CharSequence s)
判断是否包含某个字符串,原理与indexOf一致
public boolean contains(CharSequence s) {
return indexOf(s.toString()) > -1;
}
replace(char oldChar, char newChar)
字符串替换函数,oldChar要被替换的字符,newChar替换后的字符
public String replace(char oldChar, char newChar) {
// 如果新替换的字符与老字符相同,直接返回当前字符串对象
if (oldChar != newChar) {
int len = value.length; //当前字符串长度
int i = -1;
char[] val = value; //当前字符串char数组
/**
* 查询要替换的字符串位置
* 如果没找到i == len直接返回本身
*/
while (++i < len) {
if (val[i] == oldChar) {
break;
}
}
if (i < len) {
//使用当前字符串的长度新创建一个字符数组buf
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;
}