当前位置: 代码迷 >> 综合 >> JDK源码之——String
  详细解决方案

JDK源码之——String

热度:100   发布时间:2023-10-21 12:09:57.0

部分方法没有解释,有疑问或错误的地方,欢迎评论指出

/*** 1、字符串的值创建之后是无法改变的* 2、String buffers 支持可变字符串。* 3、因为String对象是不可变的,所以可以共享它们。** String str = "abc" ==> char data [] = {'a','b','c'}; String str = new String (data);*/
//Serializable 对象序列化就是把一个对象变为二进制的数据流的一种方法,通过对象序列化可以方便地实现对象的传输和存储
//CharSequence 是一个接口,表示char值的一个可读序列
//final 类不能被继承,没有子类,final类中的方法默认是final的。
public final class String implements java.io.Serializable, Comparable<String>, CharSequence {//储存字符串的值 <字符串底层实现>private final char value[];//Hash值private int hash; // Default to 0//使用JDK 1.0.2中的serialVersionUID实现互操作性private static final long serialVersionUID = -6849794470754667710L;//类字符串在序列化流协议中是特殊的private static final ObjectStreamField[] serialPersistentFields =new ObjectStreamField[0];/*** 无参构造 默认值为空 "";*/public String() {this.value = "".value;}/*** 有参构造 char[] value = original.value* @param original 原字符串*/public String(String original) {this.value = original.value;this.hash = original.hash;}/*** 带参构造* @param value char值*/public String(char value[]) {//拷贝char[] 赋值(笔者:为什么不直接=)this.value = Arrays.copyOf(value, value.length);}/*** 根据传入char 根据count 截取长度赋值给value*/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);}//count==0 直接返回""if (offset <= value.length) {this.value = "".value;return;}}// count长度过长 越界if (offset > value.length - count) {throw new StringIndexOutOfBoundsException(offset + count);}this.value = Arrays.copyOfRange(value, offset, offset+count);}/*** 传入int[]数组 根据count 截取长度赋值给value*/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;}}if (offset > codePoints.length - count) {throw new StringIndexOutOfBoundsException(offset + count);}//结束位置final int end = offset + count;//找char[]的长度int n = count;for (int i = offset; i < end; i++) {int c = codePoints[i];//(c > = MIN_VALUE && c <= MAX_VALUE) ==> (c >>> 16 == 0 [jdk运行时优化]) // MIN_VALUE = \u0000 代表的应该是NULL,输出控制台是一个空格// MAX_VALUE = \uffff \uFFFF是Java中最大的可能字符if (Character.isBmpCodePoint(c))continue;else if (Character.isValidCodePoint(c))n++;else throw new IllegalArgumentException(Integer.toString(c));}//循环入值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;elseCharacter.toSurrogates(c, v, j++);}this.value = v;}//这个构造方法已不推荐使用@Deprecatedpublic String(byte ascii[], int hibyte, int offset, int count) {checkBounds(ascii, offset, count);char value[] = new char[count];if (hibyte == 0) {for (int i = count; i-- > 0;) {value[i] = (char)(ascii[i + offset] & 0xff);}} else {hibyte <<= 8;for (int i = count; i-- > 0;) {value[i] = (char)(hibyte | (ascii[i + offset] & 0xff));}}this.value = value;}//不推荐使用@Deprecatedpublic String(byte ascii[], int hibyte) {this(ascii, hibyte, 0, ascii.length);}//用于校验字节数组边界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);}//根据字节数组构造Stringpublic String(byte bytes[]) {this(bytes, 0, bytes.length);}//StringBuffer.getValue 返回char[] (StringBuffer是不安全的,所以加同步锁)public String(StringBuffer buffer) {synchronized(buffer) {this.value = Arrays.copyOf(buffer.getValue(), buffer.length());}}//StringBuilder是线程安全的public String(StringBuilder builder) {this.value = Arrays.copyOf(builder.getValue(), builder.length());}//返回char数组的长度public int length() {return value.length;}//判断数组长度来判断字符串是否为空public boolean isEmpty() {return value.length == 0;}//返回对应下标的charpublic char charAt(int index) {if ((index < 0) || (index >= value.length)) {throw new StringIndexOutOfBoundsException(index);}return value[index];}//返回指定的字符(Unicode)public int codePointAt(int index) {if ((index < 0) || (index >= value.length)) {throw new StringIndexOutOfBoundsException(index);}return Character.codePointAtImpl(value, index, value.length);}//返回指定之前的字符(Unicode)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);}//将此字符串中的字符复制到目标字符中数组。System.arraycopy(value, 0, dst, dstBegin, value.length);}//将此字符串中的字符复制到目标字符中数组。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() {return StringCoding.encode(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) {return contentEquals((CharSequence)sb);}//判断字符串内容是否相等public boolean contentEquals(CharSequence cs) {// Argument is a StringBuffer, StringBuilderif (cs instanceof AbstractStringBuilder) {if (cs instanceof StringBuffer) {synchronized(cs) {return nonSyncContentEquals((AbstractStringBuilder)cs);}} else {return nonSyncContentEquals((AbstractStringBuilder)cs);}}// Argument is a Stringif (cs instanceof String) {return equals(cs);}// Argument is a generic CharSequencechar 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;}//忽略大小写 判断字符串内容是否相等public boolean equalsIgnoreCase(String anotherString) {return (this == anotherString) ? true: (anotherString != null)&& (anotherString.value.length == value.length)&& regionMatches(true, 0, anotherString, 0, value.length);}//字符串比较// 1."1234" 和 "123" 比较 返回 1 // 2."123" 和 "1234" 比较 返回 -1 // 3."4234" 和 "234" 比较 返回 2 // 4."Y" 和 "1" 比较 返回 40//通过示例 当一个字符串刚好为另一个字符串的一部分时,返回长度之差//         当字符串比对时,遇到第一个不相等的字符,则返回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 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 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;}//比较字符串一段值是否相等 ignoreCase是否忽略大小写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;}//判断字符串是否以prefix从toffset开始//例String str = "1234"; true = str.startsWith("123", 0);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开始public boolean startsWith(String prefix) {return startsWith(prefix, 0);}//判断字符串是否以suffix结束public boolean endsWith(String suffix) {return startsWith(suffix, value.length - suffix.value.length);}//String 的hash值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;}//字符第一次出现所在位置 (int ASCII值)不存在则返回-1//例: String str = "adcy"; 3 = str.indexOf(121);public int indexOf(int ch) {return indexOf(ch, 0);}字符串所在位置 (int ASCII值, int 开始位置)不存在则返回-1public int indexOf(int ch, int fromIndex) {final int max = value.length;if (fromIndex < 0) {fromIndex = 0;} else if (fromIndex >= max) {return -1;}if (ch < Character.MIN_SUPPLEMENTARY_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);}}// 使用补充字符处理indexOfprivate 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;}//字符最后一次出现所在位置 (int ASCII值)不存在则返回-1public int lastIndexOf(int ch) {return lastIndexOf(ch, value.length - 1);}//字符最后一次出现所在位置 (int ASCII值, int 结束位置)不存在则返回-1public 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);}}//使用补充字符处理lastIndexOfprivate 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;}//字符串第一次出现所在位置,不存在则返回-1public int indexOf(String str) {return indexOf(str, 0);}//字符串第一次出现所在位置,fromIndex 开始位置 ,不存在则返回-1public int indexOf(String str, int fromIndex) {return indexOf(value, 0, value.length,str.value, 0, str.value.length, fromIndex);}//字符串第一次出现所在位置static int indexOf(char[] source, int sourceOffset, int sourceCount,String target, int fromIndex) {return indexOf(source, sourceOffset, sourceCount,target.value, 0, target.value.length,fromIndex);}/* @param   source       被搜索的字符* @param   sourceOffset 源字符串的偏移量* @param   sourceCount  源字符串的长度* @param   target       要搜索的字符* @param   targetOffset 目标字符串的偏移量* @param   targetCount  目标字符串的长度* @param   fromIndex    开始搜索索引位置*/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;}//字符最后一次出现所在位置 不存在则返回-1public int lastIndexOf(String str) {return lastIndexOf(str, value.length);}//字符最后一次出现所在位置 fromIndex 结束位置 ,不存在则返回-1public int lastIndexOf(String str, int fromIndex) {return lastIndexOf(value, 0, value.length,str.value, 0, str.value.length, fromIndex);}static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,String target, int fromIndex) {return lastIndexOf(source, sourceOffset, sourceCount,target.value, 0, target.value.length,fromIndex);}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;}}//字符串截取, beginIndex 截取开始位置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 截取开始位置, endIndex 结束位置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 CharSequence subSequence(int beginIndex, int endIndex) {return this.substring(beginIndex, endIndex);}//拼接字符串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);}//替换 oldChar 原字符, newChar 替换字符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 boolean contains(CharSequence s) {return indexOf(s.toString()) > -1;}//替换第一次出现的字符串public String replaceFirst(String regex, String replacement) {return Pattern.compile(regex).matcher(this).replaceFirst(replacement);}//替换字符串中包含的所有字符串 regex正则  replaceAll("\\d", "*")把一个字符串所有的数字字符都换成星号;public String replaceAll(String regex, String replacement) {return Pattern.compile(regex).matcher(this).replaceAll(replacement);}//替换字符串中包含的所有字符串public String replace(CharSequence target, CharSequence replacement) {return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(this).replaceAll(Matcher.quoteReplacement(replacement.toString()));}//字符串分割public String[] split(String regex, int limit) {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 thisif (off == 0)return new String[]{this};// Add remaining segmentif (!limited || list.size() < limit)list.add(substring(off, value.length));// Construct resultint 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[] split(String regex) {return split(regex, 0);}//字符串拼接 : String.join("y", "123","123","123") ==>"123y123y123"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();}//转小写 locale语言环境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 SIGMAsrcChar == '\u0130') { // LATIN CAPITAL LETTER I WITH DOT ABOVElowerChar = 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);}//转小写 language => "en";public String toLowerCase() {return toLowerCase(Locale.getDefault());}//转大写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);}//转大写public String toUpperCase() {return toUpperCase(Locale.getDefault());}//去除头尾空格public String trim() {int len = value.length;int st = 0;char[] val = value;    /* avoid getfield opcode *///如果头部有空格 0++while ((st < len) && (val[st] <= ' ')) {st++;}//如果尾部有空格 length--while ((st < len) && (val[len - 1] <= ' ')) {len--;}//如果st和len都没有变动则头尾没有空格 返回原字符串,否则截取字符串return ((st > 0) || (len < value.length)) ? substring(st, len) : this;}public String toString() {return this;}//字符串转字符数组public char[] toCharArray() {// Cannot use Arrays.copyOf because of class initialization order issueschar 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 format(Locale l, String format, Object... args) {return new Formatter(l).format(format, args).toString();}//对象转字符串public static String valueOf(Object obj) {return (obj == null) ? "null" : obj.toString();}//字符数组转字符串 public static String valueOf(char data[]) {return new String(data);}//布尔对象转字符串public static String valueOf(boolean b) {return b ? "true" : "false";}//char对象转字符串public static String valueOf(char c) {char data[] = {c};return new String(data, true);}public static String valueOf(int i) {return Integer.toString(i);}public static String valueOf(long l) {return Long.toString(l);}public static String valueOf(float f) {return Float.toString(f);}public static String valueOf(double d) {return Double.toString(d);}}

 

  相关解决方案