字符串-编程面试10大常考算法系列(1)
Tim Chen(motion$) Lv5

题语

字符串和数组

Original

  • 如果IDE没有代码自动补全功能,那么你应该记住下面这些方法:
    1
    2
    3
    4
    5
    6
    7
    8
    // 字符串
    charAt(int x) // 获得某个索引处的字符
    length() // 字符串长度
    toCharArray() // 获得字符串对应的char数组
    // 数组
    length // 数组大小
    Arrays.sort() // 数组排序
    Arrays.toString(char[] a) // 数组转成字符串

charAt(int x)

  • 它是属于字符串的方法,功能是根据字符串的下标(从0开始)取出当前的字符。
  • 源代码:
    1
    2
    3
    4
    5
    6
    public char charAt(int index) {
    if ((index < 0) || (index >= value.length)) {
    throw new StringIndexOutOfBoundsException(index);
    }
    return value[index];
    }
  • 它的思路是:首先根据判断输入的下标是否合法,然后直接取value[index],其中value是String类中的一个字符数组,它就是为了把字符串转为字符数组而设的。

length()

  • 它是属于字符串的方法,功能是返回字符串的长度。
  • 源代码:
    1
    2
    3
    public int length() {
    return value.length;
    }
  • 不必多说,参考上文。

toCharArray()

  • 它是属于字符串的方法,功能是把字符串转换成字符串数组。
  • 源代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    /**
    * Converts this string to a new character array.
    *
    * @return a newly allocated character array whose length is the length
    * of this string and whose contents are initialized to contain
    * the character sequence represented by this 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;
    }
  • 它的思路是:先创建一个和原字符串长度一样的字符数组result[],然后通过系统的arraycopy()方法把原字符串的每一个字符对应的复制到字符数组中。其中value是String类中的一个字符数组,它就是为了把字符串转为字符数组而设的,但为什么我们不直接返回value字符数组呢?因为value是private的,不可被调用。
  • 自己实现:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    // toCharArraySelf
    public static char[] toCharArraySelf(String origin) {
    char[] result = new char[origin.length()];
    for(int i = 0; i < origin.length(); i++) {
    // System.out.println("origin.index()" +origin.charAt(i));
    result[i] = (char)origin.charAt(i);
    }
    return result;
    }

length

  • 它是属于数组的一个属性,记录着数组的长度。

Arrays.sort()

  • Arrays是Java的一个工具包,专门针对数组的操作。sort()方法是数组的排序,传入的参数是一个数组,然后把数组进行排序后返回。
  • 源代码:
    1
    2
    3
    public static void sort(char[] a) {
    DualPivotQuicksort.sort(a);
    }
  • 可以看到Java7中Arrays调用的是双基准快速排序算法(DualPivotQuicksort)。有兴趣的自行研究:QuickDualPivot.java

Arrays.toString(char[] a)

  • 它是属于Arrays工具包的一个方法,功能刚好是把数组转化为字符串。
  • 源代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    public static String toString(char[] a) {
    if (a == null)
    return "null";
    int iMax = a.length - 1;
    if (iMax == -1)
    return "[]";

    StringBuilder b = new StringBuilder();
    b.append('[');
    for (int i = 0; ; i++) {
    b.append(a[i]);
    if (i == iMax)
    return b.append(']').toString();
    b.append(", ");
    }
    }

后话

 评论