天天看点

Java高阶之String类剖析一、概述二、String 类源码剖析

String 类剖析

  • 一、概述
    • 1、为什么要深入分析 String
    • 2、String 类的官方说明
  • 二、String 类源码剖析
    • 1、构造方法
    • 2、常用 API 方法
    • 3、字节数组相关 API
    • 4、index 相关 API
      • 4.1、**Supplementary
      • 4.2、indexOf
      • 4.3、lastIndexOf
    • 5、value 相关
    • 6、其他实用 API
      • 6.1、format
      • 6.2、toCharArray()

一、概述

1、为什么要深入分析 String

String

是 Java 程序中使用频率相当高的一个类,因此值得我们深入源码去学习学习。

2、String 类的官方说明

在 String 类的 JavaDoc 中有如下描述:

String类表示字符串。 Java程序中的所有字符串文字(例如"abc" )都作为此类的实例实现。
字符串是常量; 它们的值在创建后无法更改。 字符串缓冲区支持可变字符串。 由于String对象是不可变的,因此可以共享它们。 例如:
       String str = "abc";
   
等效于:
       char data[] = {'a', 'b', 'c'};
       String str = new String(data);
   
以下是一些有关如何使用字符串的示例:
以下是一些有关如何使用字符串的示例:
       System.out.println("abc");
       String cde = "cde";
       System.out.println("abc" + cde);
       String c = "abc".substring(2,3);
       String d = cde.substring(1, 2);
   
String类包含一些方法,这些方法可以检查序列中的各个字符,比较字符串,搜索字符串,提取子字符串以及创建字符串的副本,并将所有字符均转换为大写或小写。 大小写映射基于Character类指定的Unicode标准版本。
Java语言为字符串连接运算符(+)以及将其他对象转换为字符串提供了特殊的支持。 字符串连接是通过StringBuilder (或StringBuffer )类及其append方法实现的。 字符串转换是通过toString方法实现的,该方法由Object定义并由Java中的所有类继承。 有关字符串连接和转换的其他信息,请参见Java语言规范,Gosling,Joy和Steele。
除非另有说明,否则将null参数传递给此类中的构造函数或方法将导致引发NullPointerException 。
String表示采用UTF-16格式的字符串,其中补充字符由代理对表示(有关更多信息,请参见Character类中的Unicode字符表示部分)。 索引值指的是char代码单位,因此补充字符在String使用两个位置。
除了用于处理Unicode代码单元(即, char值)的方法外, String类还提供用于处理Unicode代码点(即,字符)的方法。
           

二、String 类源码剖析

1、构造方法

String 类的构造方法中,目前以及未来还可以使用的,如下:

  • 1)
    public String() {
          this.value = "".value;
      }
               
    这个构造方法是 String 的默认构造方法,创建一个值为空字符的字符串。
  • 2)
    public String(String original) {
          this.value = original.value;
          this.hash = original.hash;
      }
               
    这个是用于将其他基本数据类型的数据转化为字符串时,经常使用的构造方法,以及用指定文本生成字符串对象时也会使用这个构造方法。
  • 3)
    public String(char value[]) {
          this.value = Arrays.copyOf(value, value.length);
      }
               
    这个构造方法用于将一个

    char

    型数组转为字符串。
  • 4)
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);
            }
            if (offset <= value.length) {
                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);
    }
           

这个构造方法用于将一个字符数组从 offset 开始的 count 个字符转为字符串。

  • 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[]
          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;
      }
               
    这个构造方法的作用,是

    分配一个新的String ,该String包含Unicode代码点数组参数的子数组中的字符。 offset参数是子数组的第一个代码点的索引,而count参数指定子数组的长度。 子数组的内容将转换为char ; 后续对int数组的修改不会影响新创建的字符串。

  • 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);
      }
               
    通过使用指定的字符集解码指定的字节子String ,构造一个新的String 。 新String的长度是字符集的函数,因此可能不等于子String的长度。这个构造方法,在网络编程中使用比较频繁,通常用在从网络中接收到字节数组转化为指定字符集的本地字符串时。
  • 7)
    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);
      }
               
    和上面的方法类似,只不过在指定字符集时,用的不是字符集的名称而是字符集的

    .class

  • 8)
    public String(byte bytes[], String charsetName)
              throws UnsupportedEncodingException {
          this(bytes, 0, bytes.length, charsetName);
      }
               
    和上面两个构造方法一样,都是用于将字节数组转为字符串,不同之处就是这个构造方法是将整个字节数组转为字符串,而前面两个字符将字节数组的指定部分内容转为字符串。
  • 9)
    public String(byte bytes[], Charset charset) {
          this(bytes, 0, bytes.length, charset);
      }
               
    上一个方法的不抛出异常的版本。
  • 10)
    public String(byte bytes[], int offset, int length) {
          checkBounds(bytes, offset, length);
          this.value = StringCoding.decode(bytes, offset, length);
      }
      public String(byte bytes[]) {
          this(bytes, 0, bytes.length);
      }
               
  • 11)
    public String(StringBuffer buffer) {
          synchronized(buffer) {
              this.value = Arrays.copyOf(buffer.getValue(), 
              buffer.length());
          }
      }
               
    这个构造方法用于将

    StringBuffer

    实例对象的值转为字符串。
  • 12)
    public String(StringBuilder builder) {
          this.value = Arrays.copyOf(builder.getValue(), builder.length());
      }
               
    用于将

    StringBuilder

    对象实例的值转为字符串对象。

String 类中光构造方法,就提供了

12

个之多,再加上接下来会进行分析的、用于操作字符串对象的方法,String 类可谓真的是提供了丰富的 API 方法。

2、常用 API 方法

主要是指操作 String 对象本身,并且不返回新的对象的方法 API,主要有如下:

1)length():用于获取字符串对象的

value

的长度,而这个 value 想当然的就是一个字符数组:

private final char value[]

。由于返回值是 int 型,因此 String 的 value 数组的最大长度也就被 int 的最大能表示的整数所限制,而这个值就是:

2^31-1

2)isEmpty():用于判断当前字符串对象的

value

的长度是否为

,是则返回 true,否则返回 false。

3)charAt(int index):获取当前字符串对象的

value

即字符数组在

index

处的字符。

4)equals(Object anObject)

这个方法,有必要贴出源代码来看一看:

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

在方法体中,首先判断当前进行比较的两个字符串对象是否是

同一个对象实例

,如果是则直接返回true,否则才进行两个字符串对象的 value 数组的遍历比较,只有当两个字符串对象的 value 数组中的每个字符都一样时,才会返回 true,否则返回 false。

5)compareTo(String anotherString):这是一个用于比较两个字符串大小的方法,其实现代码如下:

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

逻辑很明确,代码也很简单,我也多费笔墨了。

6)startsWith(String prefix, int toffset):该方法用于判断字符串对象的 value 数组是否以特定的前缀开始,其实现代码如下:

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

所使用的算法逻辑很简单,就是将匹配子串和目标字符串对齐,从下标为 0 的地方开始遍历匹配,只有当遍历完匹配子串后都没有出现不匹配的字符时,才返回 true,否则就返回 false。进行匹配时,可以指定字符串的开始进行匹配的位置,不指定则默认从 0 开始。此外,对于判断字符串对象的 value 数组是否以特定的后缀结束,用的还是这个方法,不信看源代码:

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

7)hashCode():该方法用于返回字符串对象的 hash 值,其实现代码如下:

private int hash; // Default to 0
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;
    }
           

所采用的 hash 算法就是:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

,即用一个不断更新的 h 乘于 31 再加上字符串对象 value 数组字符在 ASII 码表中的 int 值。

之所以使用 31, 是因为它是一个奇素数。如果乘数是偶数,并且乘法溢出的话,信息就会丢失,因为与2相乘等价于移位运算(低位补0)。使用素数的好处并不很明显,但是习惯上使用素数来计算散列结果。 31 有个很好的性能,即用移位和减法来代替乘法,可以得到更好的性能: 31 * i == (i << 5)- i, 现代的 VM 可以自动完成这种优化。这个公式可以很简单的推导出来。

8)replace(CharSequence target, CharSequence replacement):该方法用于将字符串对象的 value 数组中的指定字符序列替换为目标字符序列:

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

采用了链式编程流式计算来实现。与这个方法类似的还有两个方法,也是比较常用的:

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

用于替换第一次遇到的和 regex 相同的子串为 replacement。

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

用于替换字符串中所有与 regex 相同的子串为 replacement。

9)trim():用于删除字符串两边的空格:

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

10)大小写转换:这样一个看似简单的功能,实际上处理逻辑却相当麻烦,String 类中这两个方法一共占去了 91+88 行,由于代码量比较多,就不贴出源码了。

11)substring(int beginIndex, int endIndex):该方法用于获取字符串中从 beginIndex 开始到 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);
    }
           

归根到底就是生成了一个新的 String 对象实例。

  • 12)concat(String str):这个方法用于拼接字符串,即将参数中的字符串拼接到调用该方法的字符串之后。
    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);
      }
               
  • 13)split(String regex):根据 regex 划分成不同的子串数组;在实现时,调用了 split(String regex, int limit) 方法,

    limit

    控制划分后的数组数目,例如以字符串 “boo:and:foo” 为例,使用不同的 limit 值:
    regex limit arrays
      :2 { "boo", "and:foo" }
      :5 { "boo", "and", "foo" }
      :-2 { "boo", "and", "foo" }
      o 5 { "b", "", ":and:f", "", "" }
      o -2 { "b", "", ":and:f", "", "" }
      o 0 { "b", "", ":and:f" }
               
    从例子可以看出,当 limit 值小于等于 0 时,表示不限制划分后产生的数组数量。而我们经常使用的无需传 limit 参数的 split 方法,在 JDK 中就是指定了 limit 为 0,源代码如下:
    public String[] split(String regex) {
          return split(regex, 0);
      }
               

3、字节数组相关 API

String 类的实例对象,支持从字节数组转换而来,并且也提供了三个 API 用于将 String 对象转为字节数组,这三个 API 分别如下:

  • getBytes():用于将整个字符串都转为字节数组
    public byte[] getBytes() {
          return StringCoding.encode(value, 0, value.length);
      }
               
  • getBytes(String charsetName):将字符串根据指定的字符集名称转为字节数组
    public byte[] getBytes(String charsetName)
              throws UnsupportedEncodingException {
          if (charsetName == null) throw new NullPointerException();
          return StringCoding.encode(charsetName, value, 0, value.length);
      }
               
  • getBytes(Charset charset):和上面的类似,只不过该方法在指定字符集时,不是用字符集名称作为参数,而是用一个字符集对象也即

    .class

    进行传参。
  • 这三个 API 方法的核心调用都是

    static byte[] encode(String charsetName, char[] ca, int off, int len)

    方法,这是字符串编码和解码的实用程序类中的一个用于编码的方法

4、index 相关 API

String 提供了一系列与 index 相关的 API 方法,主要分为:

indexOf()

lastIndexOf()

两大类,以及一个

**Supplementary(int ch, int fromIndex)

4.1、**Supplementary

该方法用于

处理(罕见)带有补充字符的indexOf调用

,方法源代码如下:

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

是一个私有方法,也就是外部无法调用、只能在内部使用的方法。

Character.highSurrogate(ch)

方法用于

返回代表UTF-16编码中指定的补充字符(Unicode代码点)的代理对 的前导代理(高代理代码单位 )

,而

lowSurrogate(ch)

方法用于

返回代表UTF-16编码中指定的补充字符(Unicode代码点)的替代对 的尾随替代(低替代代码单元 )

,剩下的代码逻辑无非是一个遍历匹配。

4.2、indexOf

String 通过传递不同的参数,一个提供了 6 个 API,详细如下:

  • 1)public int indexOf(int ch) {

    return indexOf(ch, 0);

    }

  • 2)indexOf(int ch, int fromIndex):返回第一次出现的指定字符在此字符串内的索引,从 fromIndex 指定的索引处开始搜索。方法源代码如下:
    /**
       * The minimum value of a
       * <a href="http://www.unicode.org/glossary/#supplementary_code_point" target="_blank" rel="external nofollow" >
       * Unicode supplementary code point</a>, constant {@code U+10000}.
       *
       * @since 1.5
       */
      public static final int MIN_SUPPLEMENTARY_CODE_POINT = 0x010000;
      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 的合法性进行一番判断,如果不合法则直接返回 -1;否则判断传递进来的字符

    ch

    是否满足小于

    0x010000

    ,如果不是则调用能够处理特殊字符的 indexOf 方法,反之则进行在当前方法体中进行下一步处理——遍历匹配直到找到并返回下标,否则返回-1.第一个 indexOf 方法实际调用的也是当前这个 indexOf 方法。
  • 3)public int indexOf(String str) {

    return indexOf(str, 0);

    }

    前面两个时针对单个字符的匹配查找下标,而这一个以及下面将列出的 indexOf 是针对子串查找的。

  • 4)indexOf(String str, int fromIndex)
    public int indexOf(String str, int fromIndex) {
          return indexOf(value, 0, value.length,
                  str.value, 0, str.value.length, fromIndex);
      }
               
  • 5)
    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);
      }
               
  • 6)
    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;
      }
               
    终于寻得庐山真面目,仔细查看 JDK 源码可以发现经常出现

    一个参数列表比较多且复杂的方法通过多态进行针对性的传参和默认参数设置提供通过方法名的多个 API

    ,可谓是将面向对象编程的多态用的炉火纯青。

    这个针对子串查找匹配的最终版的逻辑:首先对fromIndex 和 targetCount 进行判断,fromIndex 就是调用indexOf 方法的字符串开始参与匹配的下标,targetCount 则是参数中子串的长度;然后在一个循环体中通过暴力算法进行子串匹配:

    首先在字符串中找到和目标串的第一个字符匹配的位置,然在这个位置的下一个位置开始与目标串的遍历匹配,当能够顺利遍历匹配完整个目标串,才返回下标值,否则返回-1

    .

    4.3、lastIndexOf

    lastIndexOf 的功能与 indexOf 相反,在字符串中寻找最后一次出现的与目标字符匹配的下标或与目标子串匹配的起始下标。

    考虑到篇幅的原因,这里就不罗列源代码了。其实,lastIndexOf 的实现逻辑和原理,与 indexOf 的基本是一致,只不过寻找的位置不同而已。

    5、value 相关

    String 类中,除了提供许多与 index 相关的 API,还提供了用于操作 value 数组的相关 API,即 valueOf 方法:
    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(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";
      }
      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);
      }
               
    针对不同数据类型的参数提供了一共 11 个 valueOF 方法,根据具体的实现代码可以分为两三类:从字符型数据转为 String、从数字型转为 String 和从对象型数据转为 String;字符型 char 数组转为 String 都是通过创建一个新的 String 对象来完成,而数字型转 String 则是利用相应的包装类的 toString() 方法来完成,对象型数据也是用 toString() 方法来转成 String 对象。

    6、其他实用 API

    6.1、format

    String 类提供了用于格式化字符串的 API,如下:
    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();
      }
               
    第二个方法的 Locale 参数指定

    格式化期间要应用的语言环境

    ,合法的语言环境有:
    • ENGLISH
    • FRENCH
    • GERMAN
    • ITALIAN
    • JAPANESE
    • KOREAN
    • CHINESE
    • SIMPLIFIED_CHINESE
    • TRADITIONAL_CHINESE
    • FRANCE
    • GERMANY
    • ITALY
    • JAPAN
    • KOREA
    • CHINA
    • PRC
    • TAIWAN
    • UK
    • US
    • CANADA
    • CANADA_FRENCH
    • ROOT

      而 format 的用法:

      Java语言的格式化打印在很大程度上受到C的printf启发。 尽管格式字符串类似于C,但是已经进行了一些自定义以适应Java语言并利用其某些功能。 而且,Java格式比C格式更严格。 例如,如果转换与标志不兼容,则将引发异常。 在C语言中,不适用的标志将被静默忽略。 因此,格式字符串旨在为C程序员所识别,但不一定与C语言完全兼容。

      相关用法示例:
    StringBuilder sb = new StringBuilder();
       // Send all output to the Appendable object sb
       Formatter formatter = new Formatter(sb, Locale.US);
    
       // Explicit argument indices may be used to re-order output.
       formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d")
       // -> " d  c  b  a"
    
       // Optional locale as the first argument can be used to get
       // locale-specific formatting of numbers.  The precision and width can be
       // given to round and align the value.
       formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E);
       // -> "e =    +2,7183"
    
       // The '(' numeric flag may be used to format negative numbers with
       // parentheses rather than a minus sign.  Group separators are
       // automatically inserted.
       formatter.format("Amount gained or lost since last statement: $ %(,.2f",
                        balanceDelta);
       // -> "Amount gained or lost since last statement: $ (6,217.58)"
       // Writes a formatted string to System.out.
       System.out.format("Local time: %tT", Calendar.getInstance());
       // -> "Local time: 13:34:18"
    
       // Writes formatted output to System.err.
       System.err.printf("Unable to open file '%1$s': %2$s",
                         fileName, exception.getMessage());
       // -> "Unable to open file 'food': No such file or directory"
       // Format a string containing a date.
       import java.util.Calendar;
       import java.util.GregorianCalendar;
       import static java.util.Calendar.*;
    
       Calendar c = new GregorianCalendar(1995, MAY, 23);
       String s = String.format("Duke's Birthday: %1$tb %1$te, %1$tY", c);
       // -> s == "Duke's Birthday: May 23, 1995"
               

6.2、toCharArray()

这个 API 方法用于将 String 转成字符数组,源代码如下:

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 native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);
           

可以看到,arraycopy 是一个本地方法,也就是说它的实现不是用 Java,而是用 C/C++ 代码。在 JDK 源码中,越底层本地方法用的就越多。