Java的String
来源:互联网 发布:淘宝侵权怎么处理 编辑:程序博客网 时间:2024/06/16 16:02
String的底层是char类型的数组,所以先需要看一下char类型。
1、char类型
Java中char类型采用16位的Unicode编码,后来由于字符集太多,超过了65536个,所以16位的Unicode已经不能满足需要了。于是自JDK5.0开始,采用代码点表示某个字符对应的代码值,代码点规定十六进制书写,并加上前缀U+,例如U+0041表示A的代码点。Unicode的代码点分为17个代码级别。第一个代码级别是基本的多语言级别(bmp),代码点从U+0000到U+FFFF,其中包括经典的Unicode代码;其余的16个附加级别,代码点从U+10000到U+10FFFF,其中包括了一些辅助字符。
在基本的多语言级别中,每个字符采用16位表示,通常称为代码单元。如下图所示:此时一个代码点只需要一个代码单元(两个字节)即可表示,即一个char字符。而辅助字符则采用一对连续的代码单元表示进行编码(即两个代码单元(四个字节,两个char字符)表示一个代码点)。
2、Sring类型
String底层是由char数组组成,length方法将返回一个UTF-16编码表示的给定字符串所需要的代码单元数量。例如:
String greeting = "Hello";
int n = greeting.length();//5
要想得到实际的长度,即代码点的数量,可以调用:
int cpCount = greeting.length(0,greeting.length());
调用s.charAt(n)将返回位置n的代码单元,n介于0 - s.length()-1之间。例如:
char first = greeting.charAt(0);//H
char last = greeting.charAt(4);//o
要想得到第i个代码点,应该使用下列语句:
int index = greeting.offsetByCodePoint(0,i);
int cp = greeting.codePointAt(index);
3、String源码
JDK:1.7;package:java.lang。省去部分重载方法。
public final class String //final,不能给被继承。 implements java.io.Serializable, Comparable<String>, CharSequence {//可序列化,可排序//String底层是char数组,被final修饰:value保存的数组引用不能改变,又没有get/set方法能访问到这个引用,//就更不可能去修改这个引用所指向的数组里的值(实际反射可以做到,但是不推荐),所以一般认为String不可变。 private final char value[]; private int hash; // Default to 0 public String() { this.value = new char[0]; //初始化为空字符串"",因为String是不可变的,所以基本不用 } public String(String original) { this.value = original.value; //初始化Sring,新字符串是该字符串的副本,基本不用 this.hash = original.hash; } public String(char value[]) { //根据char数组构建String 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); } //分配一个新的 String,它包含代码点数组参数一个子数组的字符。offset 参数是该子数组第一个代码点的索引,count 参数指定子数组的长度。 public String(int[] codePoints, int offset, int count) { if (offset < 0) { throw new StringIndexOutOfBoundsException(offset); } if (count < 0) { throw new StringIndexOutOfBoundsException(count); } if (offset > codePoints.length - count) { throw new StringIndexOutOfBoundsException(offset + count); } final int end = offset + count; int n = count; for (int i = offset; i < end; i++) { int c = codePoints[i]; if (Character.isBmpCodePoint(c)) //判断是否属于基本多语言级别,是则true,不会溢出直接下次循环,否则false continue; else if (Character.isValidCodePoint(c)) //判断codePoint是不是一个有效的Unicode码值,即是否在0000-10FFFF之间 n++; //n初始值为count,在count基础上增加 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; //若是直接转换类型即可,不会溢出 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)//使用charsetName编码方式进行解码,构造String 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(byte bytes[], String charsetName) throws UnsupportedEncodingException { this(bytes, 0, bytes.length, charsetName); } public String(byte bytes[], Charset charset) {//通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String this(bytes, 0, bytes.length, charset); } public String(byte bytes[], int offset, int length) { checkBounds(bytes, offset, length); this.value = StringCoding.decode(bytes, offset, 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) { //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 byte[] getBytes(Charset charset) { //字符串转换成给定charset转换成字节数组 if (charset == null) throw new NullPointerException(); return StringCoding.encode(charset, value, 0, value.length); } 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的实例 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) { //与StringBuffer的内容比较 synchronized (sb) { return contentEquals((CharSequence) sb); } } public boolean contentEquals(CharSequence cs) {//与CharSequence的内容比较 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) { 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) { //字符串从toffset开始,与other从ooffset开始,长度均为len,进行比较 char ta[] = value; int to = toffset; //字符串的起始位置 char pa[] = other.value; int po = ooffset; //other字符串的起始位置 // Note: toffset, ooffset, or len might be near -1>>>1. if ((ooffset < 0) || (toffset < 0) //小于0则false || (toffset > (long)value.length - len) //长度超过范围则false || (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) { // 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; } 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 boolean startsWith(String prefix) { //同上,重载方法 return startsWith(prefix, 0); } public boolean endsWith(String suffix) {//结束 return startsWith(suffix, value.length - suffix.value.length); } public int hashCode() { //hash值 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) { //第一次出现的索引,ch为代码点 return indexOf(ch, 0); } public int indexOf(int ch, int fromIndex) { //第一次出现的索引,从指定位置开始算,ch为代码点 final int max = value.length; if (fromIndex < 0) { fromIndex = 0; } else if (fromIndex >= max) { return -1; //越界了返回-1 } if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) { //MIN_SUPPLEMENTARY_CODE_POINT = 0x010000; 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); //如果为辅助字符,则要比较两个代码单元 } } /** * Handles (rare) calls of indexOf with a supplementary character. */ private int indexOfSupplementary(int ch, int fromIndex) { if (Character.isValidCodePoint(ch)) { //是否在0x010000到0x10FFFF之间 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) { //最后一次出现的索引 return lastIndexOf(ch, value.length - 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; } public int indexOf(String str) { //str第一次出现的索引 return indexOf(str, 0); } public 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, 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; } public int lastIndexOf(String str) { return lastIndexOf(str, value.length); } public 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, 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) {//截取该字符串获得子串 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);//相同则返回自身,不同则new一个 } 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); //继承CharSequence接口实现其中的方法 } public String concat(String str) { //将指定字符串连接到此字符串的结尾 int otherLen = str.length(); if (otherLen == 0) { return this; //str为空串则返回自身 } 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) {//用newChar替代oldChar返回新串 if (oldChar != newChar) { int len = value.length; int i = -1; char[] val = value; /* avoid getfield opcode */ while (++i < len) { if (val[i] == oldChar) {//找到字符串中第一次出现oldChar的位置i break; } } if (i < len) { char buf[] = new char[len]; for (int j = 0; j < i; j++) { buf[j] = val[j]; //保存第一次出现oldChar字符串之前的字符串 } while (i < len) { char c = val[i]; buf[i] = (c == oldChar) ? newChar : c; //替换之后的oldChar并存储 i++; } return new String(buf, true); } } return this; //相等则返回自身 } public boolean matches(String regex) {//正则表达式匹配 return Pattern.matches(regex, this); } public boolean contains(CharSequence s) { //包含s则true return indexOf(s.toString()) > -1; } public String replaceFirst(String regex, String replacement) {//替换正则表达式匹配到的第一个字符串 return Pattern.compile(regex).matcher(this).replaceFirst(replacement); } 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) {//从主串里面substring分割元素 list.add(substring(off, next)); off = next + 1; } else { // last one //assert (list.size() == limit - 1); list.add(substring(off, value.length));//判断模式是否启用,而且已经使用的次数大于limit off = value.length; break; } } //没有该字符,则返回完整的串 if (off == 0) return new String[]{this}; //模式阀值未超过,则添加剩余的串 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[] split(String regex) { return split(regex, 0); } public String toLowerCase(Locale 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 { 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); } 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; } 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 toUpperCase() { return toUpperCase(Locale.getDefault()); } 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 String toString() { //直接返回自身 return this; } public char[] toCharArray() {//转化成char数组 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 format(Locale l, String format, Object... args) { return new Formatter(l).format(format, args).toString(); } public static String valueOf(Object obj) {//返回Object的字符串形式 return (obj == null) ? "null" : obj.toString(); } public static String valueOf(char data[]) { return new String(data);//char 数组参数的字符串表示形式,新字符串,不影响原数组 } public static String valueOf(char data[], int offset, int count) { return new String(data, offset, count); //数组一部分变成新串 } public static String copyValueOf(char data[], int offset, int count) { return new String(data, offset, count); } public static String copyValueOf(char data[]) { return new String(data); } public static String valueOf(boolean b) {//布尔值转化为字符串值 return b ? "true" : "false"; } //当调用 intern 方法时,如果常量池已经包含一个等于此 String 对象的字符串(用 equals(Object) 方法确定),则返回池中的字符串 //否则,将此 String 对象添加到池中,并返回此 String 对象的引用。 public native String intern();}
- java的string format
- 该死的java String
- java string的hashcode
- JAVA的String 类
- java的String探讨
- java String的比较
- JAVA的String 类
- JAVA的String 类
- JAVA的String类
- JAVA的String类
- Java的String使用
- Java String 的常见问题
- JAVA的String 类
- java String的小结
- Java 的String问题
- JAVA的String 类
- Java String的substring
- Java的String类
- 第八周实践年龄几何
- -映射组成关系
- HDU 1199 Color the Ball
- java的嵌套内部类
- 输入半径,求圆的面积和周长
- Java的String
- 三天上手PHP之10:循环(while、do...while、for、foreac)
- Java 时间和日期类型的 Hibernate 映射及二进制映射及大文本的映射
- 输入三条边,判断是否可构成三角形
- linux多线程设计
- 三个数的最大值
- javaweb项目中引入struts2后web.xml的详细配置和注释
- JDBC之PreparedStatement
- 有一函数,编写一个程序,从键盘输入一个x值,程序输出y的值