1. 不变性
public final class String
implements java. io. Serializable , Comparable< String> , CharSequence {
private final char value[ ] ;
}
类使用final修饰,不可以被继承 内部维护的字节数组使用final进行修饰,内存地址改变不了,而且地址无法改变
2. 截取
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 String ( char value[ ] , int offset, int count) {
if ( offset < 0 ) {
throw new StringIndexOutOfBoundsException ( offset) ;
}
if ( count < 0 ) {
throw new StringIndexOutOfBoundsException ( count) ;
}
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;
}
3. 相等判断
public boolean equals ( Object anObject) {
if ( this == anObject) {
return true ;
}
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 ;
}
4. 替换
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 ;
}
replaceAll(a,b):批量将全部的a批量更新成b replaceFirst(a,b):将第一个a更新b