`
yanguz123
  • 浏览: 555931 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

\(^_^)/ Java中的String类

 
阅读更多

 

 

(1).String 类代表字符串。Java 程序中的所有字符串字面值(如 "abc" )都作为此类的实例实现。 

(2).字符串是常量;它们的值在创建之后不能更改。

(3).字符串缓冲区支持可变的字符串。因为 String 对象是不可变的,所以可以共享。例如: String str = "abc";等效于: char data[] = {'a', 'b', 'c'}; String str = new String(data);

(4).String 类包括的方法可用于检查序列的单个字符、比较字符串、搜索字符串、提取子字符串、创建字符串副本并将所有字符全部转换为大写或小写。大小写映射基于 Character 类指定的 Unicode 标准版。 

(5).Java 语言提供对字符串串联符号("+")以及将其他对象转换为字符串的特殊支持。

(6).字符串串联是通过 StringBuilder(或 StringBuffer)类及其 append 方法实现的。

(7).字符串转换是通过 toString 方法实现的,该方法由 Object 类定义,并可被 Java 中的所有类继承。 

(8).除非另行说明,否则将 null 参数传递给此类中的构造方法或方法将抛出 NullPointerException。 

(9).String 表示一个 UTF-16 格式的字符串,其中的增补字符由代理项对表示(有关详细信息,请参阅 Character 类中的 Unicode 字符表示形式)。

(10).索引值是指 char 代码单元,因此增补字符在 String 中占用两个位置。 

(11).String 类提供处理 Unicode 代码点(即字符)和 Unicode 代码单元(即 char 值)的方法。 

 

 

 

char charAt(int index) 

 返回指定索引处的 char 值。 

int codePointAt(int index) 

 返回指定索引处的字符(Unicode 代码点)。 

int codePointBefore(int index) 

 返回指定索引之前的字符(Unicode 代码点)。 

int codePointCount(int beginIndex, int endIndex) 

 返回此 String 的指定文本范围中的 Unicode 代码点数。 

int compareTo(String anotherString) 

 按字典顺序比较两个字符串。 

int compareToIgnoreCase(String str) 

 按字典顺序比较两个字符串,不考虑大小写。 

String concat(String str) 

 将指定字符串连接到此字符串的结尾。 

boolean contains(CharSequence s) 

 当且仅当此字符串包含指定的 char 值序列时,返回 true。 

boolean contentEquals(CharSequence cs) 

 将此字符串与指定的 CharSequence 比较。 

boolean contentEquals(StringBuffer sb) 

 将此字符串与指定的 StringBuffer 比较。 

static String copyValueOf(char[] data) 

 返回指定数组中表示该字符序列的 String。 

static String copyValueOf(char[] data, int offset, int count) 

 返回指定数组中表示该字符序列的 String。 

boolean endsWith(String suffix) 

 测试此字符串是否以指定的后缀结束。 

boolean equals(Object anObject) 

 将此字符串与指定的对象比较。 

boolean equalsIgnoreCase(String anotherString) 

 将此 String 与另一个 String 比较,不考虑大小写。 

static String format(Locale l, String format, Object... args) 

 使用指定的语言环境、格式字符串和参数返回一个格式化字符串。 

static String format(String format, Object... args) 

 使用指定的格式字符串和参数返回一个格式化字符串。 

byte[] getBytes() 

 使用平台的默认字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。 

byte[] getBytes(Charset charset) 

 使用给定的 charset 将此 String 编码到 byte 序列,并将结果存储到新的 byte 数组。 

void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin) 

 已过时。 该方法无法将字符正确转换为字节。从 JDK 1.1 起,完成该转换的首选方法是通过 getBytes() 方法,该方法使用平台的默认字符集。 

byte[] getBytes(String charsetName) 

 使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。 

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 

 将字符从此字符串复制到目标字符数组。 

int hashCode() 

 返回此字符串的哈希码。 

int indexOf(int ch) 

 返回指定字符在此字符串中第一次出现处的索引。 

int indexOf(int ch, int fromIndex) 

 返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。 

int indexOf(String str) 

 返回指定子字符串在此字符串中第一次出现处的索引。 

int indexOf(String str, int fromIndex) 

 返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。 

String intern() 

 返回字符串对象的规范化表示形式。 

boolean isEmpty() 

 当且仅当 length() 为 0 时返回 true。 

int lastIndexOf(int ch) 

 返回指定字符在此字符串中最后一次出现处的索引。 

int lastIndexOf(int ch, int fromIndex) 

 返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。 

int lastIndexOf(String str) 

 返回指定子字符串在此字符串中最右边出现处的索引。 

int lastIndexOf(String str, int fromIndex) 

 返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。 

int length() 

 返回此字符串的长度。 

boolean matches(String regex) 

 告知此字符串是否匹配给定的正则表达式。 

int offsetByCodePoints(int index, int codePointOffset) 

 返回此 String 中从给定的 index 处偏移 codePointOffset 个代码点的索引。 

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) 

 测试两个字符串区域是否相等。 

boolean regionMatches(int toffset, String other, int ooffset, int len) 

 测试两个字符串区域是否相等。 

String replace(char oldChar, char newChar) 

 返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。 

String replace(CharSequence target, CharSequence replacement) 

 使用指定的字面值替换序列替换此字符串所有匹配字面值目标序列的子字符串。 

String replaceAll(String regex, String replacement) 

 使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。 

String replaceFirst(String regex, String replacement) 

 使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。 

String[] split(String regex) 

 根据给定正则表达式的匹配拆分此字符串。 

String[] split(String regex, int limit) 

 根据匹配给定的正则表达式来拆分此字符串。 

boolean startsWith(String prefix) 

 测试此字符串是否以指定的前缀开始。 

boolean startsWith(String prefix, int toffset) 

 测试此字符串从指定索引开始的子字符串是否以指定前缀开始。 

CharSequence subSequence(int beginIndex, int endIndex) 

 返回一个新的字符序列,它是此序列的一个子序列。 

String substring(int beginIndex) 

 返回一个新的字符串,它是此字符串的一个子字符串。 

String substring(int beginIndex, int endIndex) 

 返回一个新字符串,它是此字符串的一个子字符串。 

char[] toCharArray() 

 将此字符串转换为一个新的字符数组。 

String toLowerCase() 

 使用默认语言环境的规则将此 String 中的所有字符都转换为小写。 

String toLowerCase(Locale locale) 

 使用给定 Locale 的规则将此 String 中的所有字符都转换为小写。 

String toString() 

 返回此对象本身(它已经是一个字符串!)。 

String toUpperCase() 

 使用默认语言环境的规则将此 String 中的所有字符都转换为大写。 

String toUpperCase(Locale locale) 

 使用给定 Locale 的规则将此 String 中的所有字符都转换为大写。 

String trim() 

 返回字符串的副本,忽略前导空白和尾部空白。 

static String valueOf(boolean b) 

 返回 boolean 参数的字符串表示形式。 

static String valueOf(char c) 

 返回 char 参数的字符串表示形式。 

static String valueOf(char[] data) 

 返回 char 数组参数的字符串表示形式。 

static String valueOf(char[] data, int offset, int count) 

 返回 char 数组参数的特定子数组的字符串表示形式。 

static String valueOf(double d) 

 返回 double 参数的字符串表示形式。 

static String valueOf(float f) 

 返回 float 参数的字符串表示形式。 

static String valueOf(int i) 

 返回 int 参数的字符串表示形式。 

static String valueOf(long l) 

 返回 long 参数的字符串表示形式。 

static String valueOf(Object obj) 

 返回 Object 参数的字符串表示形式。 

 

 

部分源码:

public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
	private final char value[];
	private int hash;
    private static final ObjectStreamField[] serialPersistentFields = new ObjectStreamField[0];
	
	public String() {
        this.value = new char[0];
    }
	
	public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }
	
	public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }
	
	public String(char value[], int offset, int count) {
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }
        if (count < 0) {
            throw new StringIndexOutOfBoundsException(count);
        }
        // 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 String(int[] codePoints, int offset, int count) {
        if (offset < 0) {
            throw new StringIndexOutOfBoundsException(offset);
        }
        if (count < 0) {
            throw new StringIndexOutOfBoundsException(count);
        }
        // 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;
    }
	
	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);
    }
	
	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);
    }
	
	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());
    }
	
	public int length() {
        return value.length;
    }
	
	public boolean isEmpty() {
        return value.length == 0;
    }
	
	public char charAt(int index) {
        if ((index < 0) || (index >= value.length)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return value[index];
    }
	
	public int codePointAt(int index) {
        if ((index < 0) || (index >= value.length)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return Character.codePointAtImpl(value, index, value.length);
    }
	
	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);
    }
	
	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);
    }
	
	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);
    }
	
	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);
    }
	
	public byte[] getBytes(String charsetName)
            throws UnsupportedEncodingException {
        if (charsetName == null) throw new NullPointerException();
        return StringCoding.encode(charsetName, value, 0, value.length);
    }
	
	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;
    }
	
	public boolean contentEquals(StringBuffer sb) {
        synchronized (sb) {
            return contentEquals((CharSequence) sb);
        }
    }
	
	public boolean contentEquals(CharSequence cs) {
        if (value.length != cs.length())
            return false;
        // Argument is a StringBuffer, StringBuilder
        if (cs instanceof AbstractStringBuilder) {
            char v1[] = value;
            char v2[] = ((AbstractStringBuilder) cs).getValue();
            int i = 0;
            int n = value.length;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
        // Argument is a String
        if (cs.equals(this))
            return true;
        // Argument is a generic CharSequence
        char v1[] = value;
        int i = 0;
        int n = value.length;
        while (n-- != 0) {
            if (v1[i] != cs.charAt(i))
                return false;
            i++;
        }
        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;
        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;
    }
	
	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;
        }
    }
	
	public int compareToIgnoreCase(String str) {
        return CASE_INSENSITIVE_ORDER.compare(this, str);
    }
	
	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) {
            if (ta[to++] != pa[po++]) {
                return false;
            }
        }
        return true;
    }
	
	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) {
                
                char u1 = Character.toUpperCase(c1);
                char u2 = Character.toUpperCase(c2);
                if (u1 == u2) {
                    continue;
                }
                
                if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
                    continue;
                }
            }
            return false;
        }
        return true;
    }
	
	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;
    }
	
	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;
    }
	
	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);
        }
    }
	
	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;
    }
	
	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);
        }
    }
	
	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;
    }
	
	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;
    }
	
	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;
        }
    }
	
	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 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);
    }
	
	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 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);
    }
	
	
	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
                lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
            } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
                lowerChar = Character.ERROR;
            } else {
                lowerChar = Character.toLowerCase(srcChar);
            }
            if ((lowerChar == Character.ERROR)
                    || (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
                if (lowerChar == Character.ERROR) {
                    if (!localeDependent && srcChar == '\u0130') {
                        lowerCharArray =
                                ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH);
                    } else {
                        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 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;
        }

        char[] result = new char[len]; /* may grow */
        int resultOffset = 0;  /* result may grow, so i+resultOffset
         * is the write location in result */

        /* 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 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;
    }
	
	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;
    }
	
	public static String format(String format, Object... args) {
        return new Formatter().format(format, args).toString();
    }
	
	public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }
	
	public native String intern();
	
	private static final int HASHING_SEED;

    static {
        long nanos = System.nanoTime();
        long now = System.currentTimeMillis();
        int SEED_MATERIAL[] = {
                System.identityHashCode(String.class),
                System.identityHashCode(System.class),
                (int) (nanos >>> 32),
                (int) nanos,
                (int) (now >>> 32),
                (int) now,
                (int) (System.nanoTime() >>> 2)
        };

        // Use murmur3 to scramble the seeding material.
        // Inline implementation to avoid loading classes
        int h1 = 0;

        // body
        for (int k1 : SEED_MATERIAL) {
            k1 *= 0xcc9e2d51;
            k1 = (k1 << 15) | (k1 >>> 17);
            k1 *= 0x1b873593;

            h1 ^= k1;
            h1 = (h1 << 13) | (h1 >>> 19);
            h1 = h1 * 5 + 0xe6546b64;
        }

        // tail (always empty, as body is always 32-bit chunks)

        // finalization

        h1 ^= SEED_MATERIAL.length * 4;

        // finalization mix force all bits of a hash block to avalanche
        h1 ^= h1 >>> 16;
        h1 *= 0x85ebca6b;
        h1 ^= h1 >>> 13;
        h1 *= 0xc2b2ae35;
        h1 ^= h1 >>> 16;

        HASHING_SEED = h1;
    }
	
	private transient int hash32 = 0;
	
	int hash32() {
        int h = hash32;
        if (0 == h) {
           // harmless data race on hash32 here.
           h = sun.misc.Hashing.murmur3_32(HASHING_SEED, value, 0, value.length);

           // ensure result is not zero to avoid recalcing
           h = (0 != h) ? h : 1;

           hash32 = h;
        }

        return h;
    }
}

 

分享到:
评论

相关推荐

    Java编程代码

    public class App3_1 //定义类App3_1 { public static void main(String[] args) { int a=155; float b=21.0f; System.out.println("a="+a+",b="+b); //输出a,b的值 System.out.println("a/b="+(a/b)); //...

    Java中String类中的常用方法.TXT

    简单总结可以下Java中String类中的常用方法

    cn63后台任务开发文档

    InnerPay2CreditAutoAlertMsgVO.java 注意:vo一定要继承SuperVO package nc.vo.icdm.backgroundworkplugin.innerpaytocredit; import nc.vo.pub.SuperVO; import nc.vo.pub.lang.UFDate; public class InnerPay2...

    java基础String类选择题练习题

    java基础String类选择题练习题,文档包含了答案与分析,适合学习用,本文档仅仅用于学习分享,不得用于商业用途

    介绍java中String类的方法

    介绍java中String类的方法,String类实例的创造

    JAVA 中string类的运用

    Java中String类和常用方法 实例化String对象

    java中String类型转换方法.pdf

    java中String类型转换方法.pdf

    5.javaString类.zip

    5.javaString类.zip5.javaString类.zip5.javaString类.zip5.javaString类.zip5.javaString类.zip5.javaString类.zip5.javaString类.zip5.javaString类.zip5.javaString类.zip5.javaString类.zip5.javaString类.zip5....

    javastring类的源码

    java jdk中string类的源码 ,了解string类的书写,定义和声明

    支付宝即时到账系统java程序开发包

    支付宝即时到账系统java程序开发包 Date Now_Date=new Date(); String paygateway = "https://www.alipay.com/cooperate/gateway.do?"; //'支付接口 String service = "create_direct_pay_by_user";//快速付款交易...

    83.java中String构造方法.zip

    83.java中String构造方法.zip83.java中String构造方法.zip83.java中String构造方法.zip83.java中String构造方法.zip83.java中String构造方法.zip83.java中String构造方法.zip83.java中String构造方法.zip83.java中...

    85.java中String构造方法.zip

    85.java中String构造方法.zip85.java中String构造方法.zip85.java中String构造方法.zip85.java中String构造方法.zip85.java中String构造方法.zip85.java中String构造方法.zip85.java中String构造方法.zip85.java中...

    java中String_十六进制String_byte[]之间相互转换

    java中String_十六进制String_byte[]之间相互转换

    86.java中String对象的特点.zip

    86.java中String对象的特点.zip86.java中String对象的特点.zip86.java中String对象的特点.zip86.java中String对象的特点.zip86.java中String对象的特点.zip86.java中String对象的特点.zip86.java中String对象的特点....

    java工具类去掉字符串String中的.点。android开发java程序员常用工具类

    java工具类去掉字符串String中的.点。android开发java程序员常用工具类。博文介绍:http://blog.csdn.net/qq_21376985/article/details/51482313

    webservice所需jar包

    ,String result = ""; try { Service service = new Service(); Call call = (Call) service.createCall(); call.setTargetEndpointAddress(ws_url); //远程调用路径 String targetNamespace = ...

    Java中String类的详细文档打印版

    自己整理的Java中String类的详细文档打印版

    Java的String类

    希望对各位有所帮助,关于Java String 类的小结

    StringUtil.java

    java编程中对字符串的各种方式的处理,包括(空字符串处理、判断是否是空字符串 null和"" 都返回 true、 把string array or list用给定的符号symbol连接成一个字符串、 判定第一个字符串是否等于的第二个字符串中的某...

    练习使用Java基本数据类型。使用Java的String类操作字符串和子串

    使用Java的String类操作字符串和子串。 实验内容: 1.写一个程序提示用户键入某一货币数量(以分为单位),该程序应计算出如何用最少量的1元,50分,10分和1分硬币得到该数目。如195分最少可以用一个1元硬币,1个50分...

Global site tag (gtag.js) - Google Analytics