String类源码解读

一、体系结构

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence 

1、final说明该类不能被继承
2、实现Serializable接口标识该类型的对象可用于序列化,主要表示能够在IO流中进行传输,能够在网络进行传输。
3、实现 Comparable接口,表示String类型之间的对象能够通过String类型的比较器进行比较
4、实现CharSequence接口可以提供对字符对象统一和只读的操作

二、属性
1、

private final char value[];

定义了一个用于存放字符的数组,修饰符用final,这也解释了为何String类型对象被初始化后不能够更改
2、

   private int hash; 

定义了String类型的一个32位的hash值

三、构造方法
1、

public String() {
        this.value = "".value;
    }
使用无参构造初始化的String对象的默认值为""

2、

   public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }

使用该构造方法的格式:
String str = new String(“hello”);
此时的"hello"就是参数original的具体值
通过该方式会将"hello"的value和hash码赋值给str的value和hash码
3、

  public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }

该方法通过一个字符数组来创建一个String对象。这里调用了Arrays类中的copyOf()方法,将
字符数组中每一个字符拷贝到字符串中。
4、

  public String(char value[], int offset, int count) {
        if (offset < 0) {  //如果开始位置小于0,那么抛出下标越界异常
            throw new StringIndexOutOfBoundsException(offset);
        }
        if (count <= 0) {
            if (count < 0) {//如果截取的总数目小于0,抛出下标越界异常
                throw new StringIndexOutOfBoundsException(count);
            }
            if (offset <= value.length) {//如果开始位置小于字符数组的长度并且总数小于等于0那么会将字符串的值设置空字符串。(注意是""而不是null)
                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);
    }

1)作用:取得字符数组的一部分作为String对象
2)参数:value[]:字符数组,
offset:从字符数组中开始截取的下标,
count:从截取位置开始(包括此位置)总共截取了多少个字符。
3)实现方式:对于字符数组的截取其实是通过Arrays.copyOfRange()方法实现。该方法需要传入合法的起始坐标和终点坐标。

5、

    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[]计算创建String对象对应的字符数组长度
        int n = count;
        for (int i = offset; i < end; i++) {
            int c = codePoints[i];
            if (Character.isBmpCodePoint(c))//判断该字符(Unicode代码点)是否在Basic Multilingual Plane-基本多文种平面(BMP)中
                continue;
            else if (Character.isValidCodePoint(c))//判断该代码点是不是有效的Unicode代码点
                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;
    }

1)作用:取得整数数组的一部分,并且取出的每个整数值根据Unicode编码转化为字符,最终组成字符串。
2)参数:与上一个类似,只不过第一个参数的数组类型是整型

6、

    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);
    }

1)作用:根据指定的编码格式将字符数组中指定长度的字符组成字符串
2)参数:bytes[]:字节数组
offset:开始坐标
length:截取长度
charsetName:编码格式
3)举例
byte[] a = {‘a’,‘b’,‘c’};
try {
String str = new String(a,1,2,“UTF-8”) ;
System.out.println(str);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
此时会输出bc

    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);
    }

作用:与上一个相同,不过编码参数类型有所不同

之后很多构造函数很多类似于上面写到的,关于String的构造函数就写到这里

四、普通方法
1、

public int length() {
    return value.length;
}

作用:返回字符串的长度

2、

` public boolean isEmpty() {
        return value.length == 0;
    }`
作用:判断字符串是否为空字符串。注意判断空字符串是""而不是null

3、

public char charAt(int index) {
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index];
}

1)作用:返回字符串中指定位置的字符
2)参数:index:指定字符在char数组中的索引
3)举例:
String str = “abc”;
char c = str.charAt(1);
System.out.println©;
输出结果为 b
4、

public int codePointAt(int index) {
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return Character.codePointAtImpl(value, index, value.length);
}

1)作用:返回字符串中指定位置的字符的unicode的代码点
2)参数:index:指定字符在char数组中的索引
3)举例:
String str = “abc”;
int cp = str.codePointAt(1);
System.out.println(cp);
输出结果为98

5、

 public int codePointBefore(int index) {
        int i = index - 1;
        if ((i < 0) || (i >= value.length)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return Character.codePointBeforeImpl(value, index, 0);
    }

作用:返回指定索引前的Unicode代码点值

6、

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);
}

作用:返回指定范围内的代码点数
参数:beginIndex:起始索引
endIndex:结束索引
举例:

	String str = new String("abcd");
	System.out.println(str.codePointCount(0, str.length()));

输出为4

7、

 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);
    }

作用:返回此 String 中从给定的 index 处偏移 codePointOffset 个代码点的索引。
参数:index:指定索引
codePointOffset:偏移量

8、

 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);
    }

作用:将字符从字符串复制到目标字符数组。
参数:srcBegin :要复制的第一字符的索引
srcEnd:要复制的最后一个字符的索引
char dst[]:目标字符串
dstBegin : 目标数组中的起始偏移量

9、

    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++];
        }
    }

已过时。 该方法无法将字符正确转换为字节。

10、

public byte[] getBytes(String charsetName)
            throws UnsupportedEncodingException {
        if (charsetName == null) throw new NullPointerException();
        return StringCoding.encode(charsetName, value, 0, value.length);
    }

作用:得到一个指定的编码格式的字节数组。
参数:charsetName:指定的编码格式

11、

public byte[] getBytes() {
        return StringCoding.encode(value, 0, value.length);
    }

作用:得到平台默认的字符集的字节数组

12、

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;//如果this对象和目标对象地址相同,返回true
    }
    if (anObject instanceof String) {//如果目标对象真身是String
        String anotherString = (String)anObject;//将目标对象强转为String
        int n = value.length;
        if (n == anotherString.value.length) {//当this字符串对象和目标字符串对象长度相等
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;//通过比较两个字符串中每一个字符,如果所有字符都相等,那么返回true
        }
    }
    return false;//否则返回false
}

作用:判断指定对象和目标对象是否相等是否相等
参数:anObject 目标对象
13、

public boolean contentEquals(StringBuffer sb) {
        return contentEquals((CharSequence)sb);
    }

作用:比较this字符串和StringBuffer类型对象是否相等
参数 :sb:目标字符串

14、

  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;
    }

作用:比较this字符串和AbstractStringBuilder 子类类型对象是否相等
参数:sb:AbstractStringBuilder 子类类型对象

15、

   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;
    }

作用:比较this字符串和CharSequence 类型对象是否需相等
参数:cs:CharSequence 类型对象

16、

public boolean equalsIgnoreCase(String anotherString) {
    return (this == anotherString) ? true
            : (anotherString != null)
            && (anotherString.value.length == value.length)
            && regionMatches(true, 0, anotherString, 0, value.length);
}

作用:比较两个字符串是否相等(忽略大小写)
参数:anotherString:目标字符串

17、

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;
}

作用:逐个比较两个字符串的字符。比较次数由长度小的那个字符串长度决定。
比较的字符如果不同,那么就返回这两个字符的ascii码的差值。如果在比较中前者与 后者对应字符相同,那么就返回两个字符串长度的差值
参数: anotherString:被比较的字符

18、

    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();//获取s1长度
            int n2 = s2.length();//获取s2长度
            int min = Math.min(n1, n2);
            for (int i = 0; i < min; i++) {
                char c1 = s1.charAt(i);//获取s1字符串该索引的字符
                char c2 = s2.charAt(i);//获取s2字符串该索引的字符
                if (c1 != c2) {//如果c1和c2不相等,那么将c1,c2转化为大写进行比较
                    c1 = Character.toUpperCase(c1);
                    c2 = Character.toUpperCase(c2);
                    if (c1 != c2) {//如果c1和c2不相等,那么将c1,c2转化为小写进行比较
                        c1 = Character.toLowerCase(c1);
                        c2 = Character.toLowerCase(c2);
                        if (c1 != c2) {//如何c1不等于c2
                            // No overflow because of numeric promotion
                            return c1 - c2;//返回连个字符的ascii嘛
                        }
                    }
                }
            }
            return n1 - n2;
        }

作用:对两个字符串进行比较
19、

    public boolean regionMatches(int toffset, String other, int ooffset,
            int len) {
        char ta[] = value;//this字符串的字符数组
        int to = toffset;//this字符数组的起始位置
        char pa[] = other.value;//被比较字符串的字符数组
        int po = ooffset;//被比较字符数组的起始位置
        // Note: toffset, ooffset, or len might be near -1>>>1.
        if ((ooffset < 0) || (toffset < 0)//当两个字符数组其中有起始索引<0时
                || (toffset > (long)value.length - len)
                || (ooffset > (long)other.value.length - len)) {//当起始位置位置+比较长度>字符数组长度时
            return false;//返回false
        }
        while (len-- > 0) {//依次从起始位置进行比较
            if (ta[to++] != pa[po++]) {
                return false;
            }
        }
        return true;
    }

作用:比较两个字符串的指定区域的子字符串
参数:toffset:this字符串的开始索引
other:要比较的字符串
ooffset:要比较的字符串的开始位置
len:比较的长度

20、

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;
    }

作用:比较两个字符串的指定区域的子字符串(可以选择是否忽略大小写)
参数:
ignoreCase:true时忽略大小写,false时不忽略
toffset:this字符串的开始索引
other:要比较的字符串
ooffset:要比较的字符串的开始位置
len:比较的长度
21、

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:前缀
toffset:字符串中开始查找得位置

22、

public boolean startsWith(String prefix) {
    return startsWith(prefix, 0);
}

作用:检测字符串是否以指定的前缀开始,默认从字符串第一位开始比较。
参数:
prefix:前缀

23、

public boolean endsWith(String suffix) {
    return startsWith(suffix, value.length - suffix.value.length);
}

作用:判断字符串是否以指定后缀结尾
该方法调用了startsWith(),不过参数得起始索引是value.length - suffix.value.length
参数:
suffix:后缀

24、

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;
    }

作用:返回该字符串的hashcode

25、

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);
    }
}

作用:返回在索引为fromIndex之后第一个ascii码为ch的索引值
参数:ch:字符对应的ascii码
fromIndex:开始查找的索引

26

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;
}

作用:与indexOf效果类似

27、

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);
    }
}

作用:返回从索引为fromIndex之后的字符串中最后一个ascii码为ch的字符的索引
参数:
ch:指定字符的ascii码
fromIndex:开始查找的索引

28、

public int lastIndexOf(int ch) {
    return lastIndexOf(ch, value.length - 1);
}

作用:返回在整个字符串中最后一个ascii码为ch的字符的索引

29、

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:开始得索引

30、

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);
    }

作用:从索引为beginIndex截取到索引为endIndex-1的字符串
参数:beginIndex:开始索引
endIndex:结束索引

31、

public CharSequence subSequence(int beginIndex, int endIndex) {
        return this.substring(beginIndex, endIndex);
    }

作用:根据开始索引和结束索引的返回一个字符序列
参数:
beginIndex:开始索引
endIndex:结束索引

32、

public String concat(String str) {
    int otherLen = str.length();//获取str字符串 的长度
    if (otherLen == 0) {//如果str的长度为0,那么就返回this字符串
        return this;
    }
    int len = value.length;//获取this字符串的长度
    char buf[] = Arrays.copyOf(value, len + otherLen);//新建一个字符数组,长度为this长度与str长度之和。并且和将this字符串的值赋值给该字符数组
    str.getChars(buf, len);//通过getChars()方法,将字符复制到buf字符数组
    return new String(buf, true);//通过字符数组返回一个新的字符串
}

作用:将str字符串连接到this字符串之后,组成一个新的字符串
参数:
str:要连接的字符串

33、

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) {//开始从索引最小时遍历字符数组,当找到了与oldChar相同字符时停止遍历
                if (val[i] == oldChar) {
                    break;
                }
            }
            if (i < len) {
                char buf[] = new char[len];//创建新的字符数组
                for (int j = 0; j < i; j++) {
                    buf[j] = val[j];//在oldChar索引之前将旧的字符数组的值一次赋值给新的字符数组
                }
                while (i < len) {//将oldChar索引处将oleChar替换成newChar
                    char c = val[i];
                    buf[i] = (c == oldChar) ? newChar : c;
                    i++;
                }
                return new String(buf, true);
            }
        }
        return this;
    }

作用:用newChar替换字符串中的oldChar
参数:
newChar:新的字符
oldChar:旧的字符
举例:
String str = new String(“dsfd”);
str = str.replace(‘d’,‘a’);
System.out.println(str);
输出为
asfa

34、

public boolean matches(String regex) {
    return Pattern.matches(regex, this);
}

作用:
检测字符串是否匹配给定的正则表达式。
参数:
regex:匹配字符串的正则表达式

35、

public boolean contains(CharSequence s) {
    return indexOf(s.toString()) > -1;
}

作用:判断this字符串是否包换子字符序列。调用了indexOff(),如果在this字符串中s.toString的索引值不为-1,那么说明该字符序列这个字符串中。
参数:
s:判断是否还有的字符序列

36、

public String replaceFirst(String regex, String replacement) {
    return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
}

作用:用字符串replacement替换字符串中第一个regex子字符串
参数:
regex:在字符串你中将被替换的字符串
replacement:替换regex的字符串
举例:
String str = “hello world world”;
str = str.replaceFirst(“world”, “friend”);
System.out.println(str);
输出:hello friend world

37、

  public String replaceAll(String regex, String replacement) {
        return Pattern.compile(regex).matcher(this).replaceAll(replacement);
    }

作用:
字符串replacement替换字符串中所有regex子字符串
regex:在字符串你中将被替换的字符串
replacement:替换regex的字符串
举例:
String str = “hello world world”;
str = str.replaceFirst(“world”, “friend”);
System.out.println(str);
输出:hello friend friend

38、

public String replace(CharSequence target, CharSequence replacement) {
        return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
                this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
    }

作用:
字符序列replacement替换字符串中所有为regex的字符序列
参数:
regex:在字符串你中将被替换的字符序列
replacement:替换regex的字符序列

39、

  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);
    }

作用:按照指定的分隔符regex,分隔字符串
参数:regex:以regex进行分割
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, ]

40、

public String[] split(String regex) {
        return split(regex, 0);
    }

作用:使用regex分割字符串,并且以最大分割次数分割,但是分割结果会舍弃末位的空串
参数:regex:分隔符

41、

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通过多个delimiter连接组成该字符串
参数:
delimiter:分隔符
elements:要加入的元素
举例:
String msg = String.join("-", “j”,“a”,“v”,“a”);
System.out.println(msg);
输出 :j-a-v-a

42、

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();
}

作用:返回字符串,将集合elements中的元素通过多个delimiter连接组成该字符串
参数:
delimiter :用于分离 elements中的每一个的 elements序列字符串
elements :一个 Iterable ,将其 elements连接在一起。
举例:
List strings = new LinkedList<>();
strings.add(“Java”);
strings.add(“is”);
strings.add(“cool”);
String message = String.join("-", strings);
输出 Java-is-cool

43、
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);
}

作用:将字符串中的字符使用给定Locale的规则转换为小写。
参数:
locale:默认使用的情况下,转换规则为这个语言环境。

44、

public String toLowerCase() {
    return toLowerCase(Locale.getDefault());
}

作用:将字符串转化为小写。该方法调用了toLowerCase(Locale locale),并且参数locale是为 Locale.getDefault(),即默认语言环境的规则

45、

 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);
    }

作用:将字符串中的字符使用给定Locale的规则转换为大写。
参数:
locale:默认使用的情况下,转换规则为这个语言环境。

46、

public String toUpperCase() {
    return toUpperCase(Locale.getDefault());
}

作用:使用默认语言环境的规则将此String中的所有字符转换为大写。 此方法调用了toUpperCase(Locale.getDefault()) 。

47、

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] <= ' ')) {//从右向左获取第一个不为空格的字符的索引+1
        len--;
    }
    return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}

作用:返回次字符串,并删除此字符串开头和结尾的所有空格
例子:
String str = " helloWorld ";
str = str.trim();
System.out.println(str);
输出 helloWorld

48、

public String toString() {
    return this;
}

作用:重写了Object的toString(),返回该字符串本身

49、

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;
}

作用:将此字符串转换为新的字符数组

50、

public static String format(String format, Object... args) {
    return new Formatter().format(format, args).toString();
}

作用:使用指定的格式字符串和参数返回格式化的字符串。
参数:
format:格式化说明的字符串
args :格式字符串中格式说明符引用的参数
转化规则和如何转化网上有很多解析,这里就不举例。

51、

public static String format(Locale l, String format, Object... args) {
    return new Formatter(l).format(format, args).toString();
}

作用:使用指定的区域设置,格式字符串和参数返回格式化的字符串。
参数:
l:格式化期间应用的locale。 如果l是null ,则不应用本地化
format:格式化说明的字符串
args :格式字符串中格式说明符引用的参数
转化规则和如何转化网上有很多解析,这里就不举例。

52、

 public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

作用:将一个Object对象转化为String
参数:要转化的Object对象

53、

public static String valueOf(char data[]) {
    return new String(data);
}

作用:将一个字符数组转换为字符串
参数:
data:要转化的字符数组

54、

    public static String valueOf(char data[], int offset, int count) {
        return new String(data, offset, count);
    }

作用:将一个字符数组中指定的子字符数组转换为字符串
参数:
data:字符数组
offset:子字符数组在字数数组中的初始偏移量。
count:子字符数组的长度
例子:
char data[] = {‘a’,‘b’,‘c’,‘d’};
System.out.println(String.valueOf(data,1,2));
输出: ab

55、

public static String valueOf(boolean b) {
    return b ? "true" : "false";
}

作用:将boolean类型的参数以String的方式输出
参数:
b:boolean类型的参数
例子:
System.out.println(String.valueOf(true));
System.out.println(String.valueOf(false));
输出:
true
false

此时true和false均为String类型

56、

  public static String valueOf(int i) {
        return Integer.toString(i);
    }

作用:将int类型的参数转化为String类型
参数:
i:要转化的int类型参数

57、

public static String valueOf(long l) {
    return Long.toString(l);
}

作用:将long类型的参数转化为String类型
参数:
l:要转化的long类型参数

58、

   public static String valueOf(float f) {
        return Float.toString(f);
    }

作用:将float类型的参数转化为String类型
参数:
f:要转化的float类型参数

59、

  public static String valueOf(double d) {
        return Double.toString(d);
    }

作用:将double 类型的参数转化为String类型
参数:
d:要转化的double 类型参数

60、

 public native String intern();

作用:返回字符串的规范表示。当调用intern()方法的时候,如果字符串常量池中已经包含了此String类型的字符串(是否包含通过equals确定)。如果池中有与此相等字符串,那么就放回池中的字符串,如果没有,那么就在池中建立此String类型对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值