- /** The value is used for character storage. */
private final char value[];
final 表明字符串的内容是不可变的,一旦赋予,不能改变。 - startsWith: prefix的长度决定匹配的字符数组数量,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;
}
- subString调用String(char value[], int offset, int count)创建子串,但是底层仍旧使用System.arraycopy方法实现。
- replace(char oldChar, char 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) { //find the first oldChar
break;
}
}
if (i < len) {
char buf[] = new char[len]; //create a new array of char
for (int j = 0; j < i; j++) { //copy value into new char //array before index of first oldchar
buf[j] = val[j];
}
while (i < len) {
char c = val[i]; //start to replace oldChar of newChar from first index of oldChar on.
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(buf, true);
}
}
return this;
}
- split(String regex, int limit):
javadoc的解释如下:
(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.
当regex是一个字符时,确保该字符不是".$|()[{~?*+\"中的一个,当regex是两个字符时,匹配第二个字符。
- (@since 1.8:) static String join(CharSequence delimiter, CharSequence… elements): 将elements里的多个String用delimiter连接起来。
- intern()方法: native方法。
* A pool of strings, initially empty, is maintained privately by the
* class {@code String}.
* <p>
* When the intern method is invoked, if the pool already contains a
* string equal to this {@code String} object as determined by
* the {@link #equals(Object)} method, then the string from the pool is
* returned. Otherwise, this {@code String} object is added to the
* pool and a reference to this {@code String} object is returned.
* <p>
* It follows that for any two strings {@code s} and {@code t},
* {@code s.intern() == t.intern()} is {@code true}
* if and only if {@code s.equals(t)} is {@code true}.
上面这段话的意思就是,JVM维护了一个String的pool,当pool中存在某个string时,新建一个同样值的String时直接返回已有String的一个引用,那么intern()方法就反映了string的值是否相同,有String s和String t,当s.equals(t)时,s.intern()==t.intern()。