Java高级进阶之String实现源码详解

开发 后端
String类的一个最大特性是不可修改性,而导致其不可修改的原因是在String内部定义了一个常量数组,因此每次对字符串的操作实际上都会另外分配分配一个新的常量数组空间;

[[423318]]

前言

String类的一个最大特性是不可修改性,而导致其不可修改的原因是在String内部定义了一个常量数组,因此每次对字符串的操作实际上都会另外分配分配一个新的常量数组空间;

那今天我们就来分析一波

一、String实现源码分析

1、String的定义

  1. public final class String implements java.io.Serializable, Comparable, CharSequence 

从上,我们可以看出几个重点:

String是一个final类,既不能被继承的类

String类实现了java.io.Serializable接口,可以实现序列化

String类实现了Comparable,可以用于比较大小(按顺序比较单个字符的ASCII码)

String类实现了 CharSequence 接口,表示是一个有序字符的序列,因为String的本质是一个char类型数组

2、字段属性

  1. //用来存字符串,字符串的本质,是一个final的char型数组 
  2.  private final char value[];                                          
  3.  //缓存字符串的哈希 
  4.  private int hash;    // Default to 0                                 
  5.  //实现序列化的标识 
  6.  private static final long serialVersionUID = -6849794470754667710L;  

这里需要注意的重点是:

private final char value[]这是String字符串的本质,是一个字符集合,而且是final的,是不可变的

3、构造函数

  1.  /** 01 
  2. * 这是一个经常会使用的String的无参构造函数. 
  3. * 默认将""空字符串的value赋值给实例对象的value,也是空字符 
  4. * 相当于深拷贝了空字符串"" 
  5. */ 
  6. public String() { 
  7.         this.value = "".value; 
  8.     } 
  9. /** 02 
  10. * 这是一个有参构造函数,参数为一个String对象 
  11. * 将形参的value和hash赋值给实例对象作为初始化 
  12. * 相当于深拷贝了一个形参String对象 
  13. */ 
  14.     public String(String original) { 
  15.         this.value = original.value; 
  16.         this.hash = original.hash; 
  17.     } 
  18. /** 03 
  19. * 这是一个有参构造函数,参数为一个char字符数组 
  20. * 虽然我不知道为什么要Arrays.copyOf去拷贝,而不直接this.value = value; 
  21. * 意义就是通过字符数组去构建一个新的String对象 
  22. */ 
  23.     public String(char value[]) { 
  24.         this.value = Arrays.copyOf(value, value.length); 
  25.     } 
  26. /** 04 
  27. * 这是一个有参构造函数,参数为char字符数组,offset(起始位置,偏移量),count(个数) 
  28. * 作用就是在char数组的基础上,从offset位置开始计数count个,构成一个新的String的字符串 
  29. * 意义就类似于截取count个长度的字符集合构成一个新的String对象 
  30. */ 
  31.     public String(char value[], int offset, int count) { 
  32.         if (offset < 0) {        //如果起始位置小于0,抛异常 
  33.             throw new StringIndexOutOfBoundsException(offset); 
  34.         } 
  35.         if (count <= 0) { 
  36.             if (count < 0) {     //如果个数小于0,抛异常 
  37.                 throw new StringIndexOutOfBoundsException(count); 
  38.             } 
  39.             if (offset <= value.length) {      //在count = 0的前提下,如果offset<=len,则返回"" 
  40.                 this.value = "".value; 
  41.                 return
  42.             } 
  43.         } 
  44.         // Note: offset or count might be near -1>>>1. 
  45.         //如果起始位置>字符数组长度 - 个数,则无法截取到count个字符,抛异常 
  46.         if (offset > value.length - count) {  
  47.             throw new StringIndexOutOfBoundsException(offset + count); 
  48.         } 
  49.         //重点,从offset开始,截取到offset+count位置(不包括offset+count位置) 
  50.         this.value = Arrays.copyOfRange(value, offset, offset+count);  
  51.     } 
  52. /** 05 
  53. * 这是一个有参构造函数,参数为int字符数组,offset(起始位置,偏移量),count(个数) 
  54. * 作用跟04构造函数差不多,但是传入的不是char字符数组,而是int数组。 
  55. * 而int数组的元素则是字符对应的ASCII整数值 
  56. * 例子:new String(new int[]{97,98,99},0,3);   output: abc 
  57. */ 
  58.     public String(int[] codePoints, int offset, int count) { 
  59.         if (offset < 0) { 
  60.             throw new StringIndexOutOfBoundsException(offset); 
  61.         } 
  62.         if (count <= 0) { 
  63.             if (count < 0) { 
  64.                 throw new StringIndexOutOfBoundsException(count); 
  65.             } 
  66.             if (offset <= codePoints.length) { 
  67.                 this.value = "".value; 
  68.                 return
  69.             } 
  70.         } 
  71.         // Note: offset or count might be near -1>>>1. 
  72.         if (offset > codePoints.length - count) { 
  73.             throw new StringIndexOutOfBoundsException(offset + count); 
  74.         }   
  75. //以上都是为了处理offset和count的正确性,如果有错,则抛异常 
  76.         final int end = offset + count
  77.         // Pass 1: Compute precise size of char[] 
  78.         int n = count
  79.         for (int i = offset; i < end; i++) { 
  80.             int c = codePoints[i]; 
  81.             if (Character.isBmpCodePoint(c)) 
  82.                 continue
  83.             else if (Character.isValidCodePoint(c)) 
  84.                 n++; 
  85.             else throw new IllegalArgumentException(Integer.toString(c)); 
  86.         } 
  87. //上面关于BMP什么的,我暂时也没看懂,猜想关于验证int数据的正确性,通过上面的测试就进入下面的算法 
  88.         // Pass 2: Allocate and fill in char[] 
  89.         final char[] v = new char[n]; 
  90.         for (int i = offset, j = 0; i < end; i++, j++) {  //从offset开始,到offset + count 
  91.             int c = codePoints[i]; 
  92.             if (Character.isBmpCodePoint(c)) 
  93.                 v[j] = (char)c;   //将Int类型显式缩窄转换为char类型 
  94.             else 
  95.                 Character.toSurrogates(c, v, j++); 
  96.         } 
  97.         this.value = v; //最后将得到的v赋值给String对象的value,完成初始化 
  98.     } 
  99. /****这里把被标记为过时的构造函数去掉了***/ 
  100. /** 06 
  101. * 这是一个有参构造函数,参数为byte数组,offset(起始位置,偏移量),长度,和字符编码格式 
  102. * 就是传入一个byte数组,从offset开始截取length个长度,其字符编码格式为charsetName,如UTF-8 
  103. * 例子:new String(bytes, 2, 3, "UTF-8"); 
  104. */ 
  105.     public String(byte bytes[], int offset, int length, String charsetName) 
  106.             throws UnsupportedEncodingException { 
  107.         if (charsetName == null
  108.             throw new NullPointerException("charsetName"); 
  109.         checkBounds(bytes, offset, length); 
  110.         this.value = StringCoding.decode(charsetName, bytes, offset, length); 
  111.     } 
  112. /** 07 
  113. * 类似06 
  114. */ 
  115.     public String(byte bytes[], int offset, int length, Charset charset) { 
  116.         if (charset == null
  117.             throw new NullPointerException("charset"); 
  118.         checkBounds(bytes, offset, length); 
  119.         this.value =  StringCoding.decode(charset, bytes, offset, length); 
  120.     } 
  121. /** 08 
  122. * 这是一个有参构造函数,参数为byte数组和字符集编码 
  123. * 用charsetName的方式构建byte数组成一个String对象 
  124. */ 
  125.     public String(byte bytes[], String charsetName) 
  126.             throws UnsupportedEncodingException { 
  127.         this(bytes, 0, bytes.length, charsetName); 
  128.     } 
  129. /** 09 
  130. * 类似08 
  131. */ 
  132.     public String(byte bytes[], Charset charset) { 
  133.         this(bytes, 0, bytes.length, charset); 
  134.     } 
  135. /** 10 
  136. * 这是一个有参构造函数,参数为byte数组,offset(起始位置,偏移量),length(个数) 
  137. * 通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String。 
  138. *  
  139. */ 
  140.     public String(byte bytes[], int offset, int length) { 
  141.         checkBounds(bytes, offset, length); 
  142.         this.value = StringCoding.decode(bytes, offset, length); 
  143.     } 
  144. /** 11 
  145. * 这是一个有参构造函数,参数为byte数组 
  146. * 通过使用平台默认字符集编码解码传入的byte数组,构造成一个String对象,不需要截取 
  147. *  
  148. */ 
  149.     public String(byte bytes[]) { 
  150.         this(bytes, 0, bytes.length); 
  151.     } 
  152. /** 12 
  153. * 有参构造函数,参数为StringBuffer类型 
  154. * 就是将StringBuffer构建成一个新的String,比较特别的就是这个方法有synchronized锁 
  155. * 同一时间只允许一个线程对这个buffer构建成String对象 
  156. */ 
  157.     public String(StringBuffer buffer) { 
  158.         synchronized(buffer) { 
  159.             this.value = Arrays.copyOf(buffer.getValue(), buffer.length()); //使用拷贝的方式 
  160.         } 
  161.     } 
  162. /** 13 
  163. * 有参构造函数,参数为StringBuilder 
  164. * 同12差不多,只不过是StringBuilder的版本,差别就是没有实现线程安全 
  165. */ 
  166.     public String(StringBuilder builder) { 
  167.         this.value = Arrays.copyOf(builder.getValue(), builder.length()); 
  168.     } 
  169. /** 14 
  170. * 这个构造函数比较特殊,有用的参数只有char数组value,是一个不对外公开的构造函数,没有访问修饰符 
  171. * 加入这个share的只是为了区分于String(char[] value)方法,用于重载,功能类似于03,我也在03表示过疑惑。 
  172. * 为什么提供这个方法呢,因为性能好,不需要拷贝。为什么不对外提供呢?因为对外提供会打破value为不变数组的限制。 
  173. * 如果对外提供这个方法让String与外部的value产生关联,如果修改外不的value,会影响String的value。所以不能 
  174. * 对外提供 
  175. */ 
  176.     String(char[] value, boolean share) { 
  177.         // assert share : "unshared not supported"
  178.         this.value = value; 
  179.     } 

展示了总共14种构造方法:

  • 可以构造空字符串对象,既"";
  • 可以根据String,StringBuilder,StringBuffer构造字符串对象;
  • 可以根据char数组,其子数组构造字符串对象;
  • 可以根据int数组,其子数组构造字符串对象;
  • 可以根据某个字符集编码对byte数组,其子数组解码并构造字符串对象;

4、长度和是否为空函数

  1. public int length() {       //所以String的长度就是一个value的长度 
  2.         return value.length; 
  3.     } 
  4.     public boolean isEmpty() {  //当char数组的长度为0,则代表String为"",空字符串 
  5.         return value.length == 0; 
  6.     } 

5、charAt、codePointAt类型函数

  1. /** 
  2.    * 返回String对象的char数组index位置的元素 
  3.    */ 
  4.    public char charAt(int index) { 
  5.         if ((index < 0) || (index >= value.length)) {   //index不允许小于0,不允许大于等于String的长度 
  6.             throw new StringIndexOutOfBoundsException(index); 
  7.         } 
  8.         return value[index]; //返回 
  9.     } 
  10.    /** 
  11.     * 返回String对象的char数组index位置的元素的ASSIC码(int类型) 
  12.     */ 
  13.     public int codePointAt(int index) { 
  14.         if ((index < 0) || (index >= value.length)) { 
  15.             throw new StringIndexOutOfBoundsException(index); 
  16.         } 
  17.         return Character.codePointAtImpl(value, index, value.length); 
  18.     } 
  19.    /** 
  20.     * 返回index位置元素的前一个元素的ASSIC码(int型) 
  21.     */ 
  22.     public int codePointBefore(int index) { 
  23.         int i = index - 1;  //获得index前一个元素的索引位置 
  24.         if ((i < 0) || (i >= value.length)) { //所以,index不能等于0,因为i = 0 - 1 = -1 
  25.             throw new StringIndexOutOfBoundsException(index); 
  26.         } 
  27.         return Character.codePointBeforeImpl(value, index, 0); 
  28.     } 
  29.    /** 
  30. * 方法返回的是代码点个数,是实际上的字符个数,功能类似于length() 
  31. * 对于正常的String来说,length方法和codePointCount没有区别,都是返回字符个数。 
  32. * 但当String是Unicode类型时则有区别了。 
  33. * 例如:String str = “/uD835/uDD6B” (即使 'Z' ), length() = 2 ,codePointCount() = 1 
  34. */ 
  35.     public int codePointCount(int beginIndex, int endIndex) { 
  36.         if (beginIndex < 0 || endIndex > value.length || beginIndex > endIndex) { 
  37.             throw new IndexOutOfBoundsException(); 
  38.         } 
  39.         return Character.codePointCountImpl(value, beginIndex, endIndex - beginIndex); 
  40.     } 
  41.    /** 
  42. * 也是相对Unicode字符集而言的,从index索引位置算起,偏移codePointOffset个位置,返回偏移后的位置是多少 
  43. * 例如,index = 2 ,codePointOffset = 3 ,maybe返回 5  
  44. */ 
  45.     public int offsetByCodePoints(int indexint codePointOffset) { 
  46.         if (index < 0 || index > value.length) { 
  47.             throw new IndexOutOfBoundsException(); 
  48.         } 
  49.         return Character.offsetByCodePointsImpl(value, 0, value.length, 
  50.                 index, codePointOffset); 
  51.     } 

只有一个charAt()是针对字符而言的,就是寻找第index位置的字符是什么;

ChatAt是实现CharSequence 而重写的方法,是一个有序字符集的方法;

6、getChar、getBytes类型函数

  1.   /** 
  2. * 这是一个不对外的方法,是给String内部调用的,因为它是没有访问修饰符的,只允许同一包下的类访问 
  3. * 参数:dst[]是目标数组,dstBegin是目标数组的偏移量,既要复制过去的起始位置(从目标数组的什么位置覆盖) 
  4. * 作用就是将String的字符数组value整个复制到dst字符数组中,在dst数组的dstBegin位置开始拷贝 
  5. *  
  6. */ 
  7. void getChars(char dst[], int dstBegin) { 
  8.         System.arraycopy(value, 0, dst, dstBegin, value.length); 
  9.     } 
  10.    /** 
  11. * 得到char字符数组,原理是getChars() 方法将一个字符串的字符复制到目标字符数组中。  
  12. * 参数:srcBegin是原始字符串的起始位置,srcEnd是原始字符串要复制的字符末尾的后一个位置(既复制区域不包括srcEnd) 
  13. * dst[]是目标字符数组,dstBegin是目标字符的复制偏移量,复制的字符从目标字符数组的dstBegin位置开始覆盖。 
  14. */ 
  15.     public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) { 
  16.         if (srcBegin < 0) {           //如果srcBegin小于,抛异常 
  17.             throw new StringIndexOutOfBoundsException(srcBegin); 
  18.         } 
  19.     *    if (srcEnd > value.length) {  //如果srcEnd大于字符串的长度,抛异常 
  20.             throw new StringIndexOutOfBoundsException(srcEnd); 
  21.         } 
  22.         if (srcBegin > srcEnd) {      //如果原始字符串其实位置大于末尾位置,抛异常 
  23.             throw new StringIndexOutOfBoundsException(srcEnd - srcBegin); 
  24.         } 
  25.         System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin); 
  26.     } 
  27.    /****去除被标记过时的方法****/ 
  28.    /** 
  29.     * 获得charsetName编码格式的bytes数组 
  30. */ 
  31.     public byte[] getBytes(String charsetName) 
  32.             throws UnsupportedEncodingException { 
  33.         if (charsetName == null) throw new NullPointerException(); 
  34.         return StringCoding.encode(charsetName, value, 0, value.length); 
  35.     } 
  36.    /** 
  37.     * 与上个方法类似,但charsetName和charset的区别,我还没搞定,搞懂来再更新 
  38. */ 
  39.     public byte[] getBytes(Charset charset) { 
  40.         if (charset == null) throw new NullPointerException(); 
  41.         return StringCoding.encode(charset, value, 0, value.length); 
  42.     } 
  43. /** 
  44.     * 使用平台默认的编码格式获得bytes数组 
  45. */ 
  46.     public byte[] getBytes() { 
  47.         return StringCoding.encode(value, 0, value.length); 
  48.     } 
  • getChars是没有返回值的,原理是通过System.arraycopy方法来实现的,不需要返回值。所以被覆盖的字符数组是需要具体存在的;
  • getBytes是有返回值的;

7、equal类函数(是否相等)

  1. /** 
  2. * String的equals方法,重写了Object的equals方法(区分大小写) 
  3. * 比较的是两个字符串的值是否相等 
  4. * 参数是一个Object对象,而不是一个String对象。这是因为重写的是Object的equals方法,所以是Object 
  5. * 如果是String自己独有的方法,则可以传入String对象,不用多此一举 
  6. *  
  7. * 实例:str1.equals(str2) 
  8. */ 
  9. public boolean equals(Object anObject) { 
  10.         if (this == anObject) {   //首先判断形参str2是否跟当前对象str1是同一个对象,既比较地址是否相等 
  11.             return true;          //如果地址相等,那么自然值也相等,毕竟是同一个字符串对象 
  12.         } 
  13.         if (anObject instanceof String) {  //判断str2对象是否是一个String类型,过滤掉非String类型的比较 
  14.             String anotherString = (String)anObject; //如果是String类型,转换为String类型 
  15.             int n = value.length;                    //获得当前对象str1的长度 
  16.             if (n == anotherString.value.length) {   //比较str1的长度和str2的长度是否相等 
  17.                                                      //如是进入核心算法 
  18.                 char v1[] = value;                   //v1为当前对象str1的值,v2为参数对象str2的值 
  19.                 char v2[] = anotherString.value; 
  20.                 int i = 0;                           //就类似于forint i =0的作用,因为这里使用while 
  21.                 while (n-- != 0) {                   //每次循环长度-1,直到长度消耗完,循环结束  
  22.                     if (v1[i] != v2[i])              //同索引位置的字符元素逐一比较 
  23.                         return false;                //只要有一个不相等,则返回false 
  24.                     i++; 
  25.                 } 
  26.                 return true;                         //如比较期间没有问题,则说明相等,返回true 
  27.             } 
  28.         } 
  29.         return false
  30.     } 
  1. /** 
  2. * 这也是一个String的equals方法,与上一个方法不用,该方法(不区分大小写),从名字也能看出来 
  3. * 是对String的equals方法的补充。 
  4. * 这里参数这是一个String对象,而不是Object了,因为这是String本身的方法,不是重写谁的方法 
  5. */ 
  6. public boolean equalsIgnoreCase(String anotherString) { 
  7.         return (this == anotherString) ? true                   //一样,先判断是否为同一个对象 
  8.                 : (anotherString != null)  
  9.                 && (anotherString.value.length == value.length) //再判断长度是否相等 
  10.                 && regionMatches(true, 0, anotherString, 0, value.length);  //再执行regionMatchs方法  
  11.     } 
  12. /** 
  13. * 这是一个公有的比较方法,参数是StringBuffer类型 
  14. * 实际调用的是contentEquals(CharSequence cs)方法,可以说是StringBuffer的特供版 
  15. */ 
  16.     public boolean contentEquals(StringBuffer sb) { 
  17.         return contentEquals((CharSequence)sb); 
  18.     } 
  19. /** 
  20. * 这是一个私有方法,特供给比较StringBuffer和StringBuilder使用的。 
  21. * 比如在contentEquals方法中使用,参数是AbstractStringBuilder抽象类的子类 
  22. */ 
  23.     private boolean nonSyncContentEquals(AbstractStringBuilder sb) { 
  24.         char v1[] = value;               //当前String对象的值 
  25.         char v2[] = sb.getValue();       //AbstractStringBuilder子类对象的值 
  26.         int n = v1.length;               //后面就不说了,其实跟equals方法是一样的,只是少了一些判断 
  27.         if (n != sb.length()) { 
  28.             return false
  29.         } 
  30.         for (int i = 0; i < n; i++) { 
  31.             if (v1[i] != v2[i]) { 
  32.                 return false
  33.             } 
  34.         } 
  35.         return true
  36.     } 
  37. /** 
  38. * 这是一个常用于String对象跟StringBuffer和StringBuilder比较的方法 
  39. * 参数是StringBuffer或StringBuilder或String或CharSequence 
  40. * StringBuffer和StringBuilder和String都实现了CharSequence接口 
  41. */ 
  42.     public boolean contentEquals(CharSequence cs) { 
  43.         // Argument is a StringBuffer, StringBuilder 
  44.         if (cs instanceof AbstractStringBuilder) {   //如果是AbstractStringBuilder抽象类或其子类 
  45.             if (cs instanceof StringBuffer) {        //如果是StringBuffer类型,进入同步块 
  46.                 synchronized(cs) { 
  47.                    return nonSyncContentEquals((AbstractStringBuilder)cs); 
  48.                 } 
  49.             } else {                                 //如果是StringBuilder类型,则进入非同步块 
  50.                 return nonSyncContentEquals((AbstractStringBuilder)cs); 
  51.             } 
  52.         } 
  53. /***下面就是String和CharSequence类型的比较算法*****/ 
  54.         // Argument is a String 
  55.         if (cs instanceof String) {                     
  56.             return equals(cs); 
  57.         } 
  58.         // Argument is a generic CharSequence 
  59.         char v1[] = value; 
  60.         int n = v1.length; 
  61.         if (n != cs.length()) { 
  62.             return false
  63.         } 
  64.         for (int i = 0; i < n; i++) { 
  65.             if (v1[i] != cs.charAt(i)) { 
  66.                 return false
  67.             } 
  68.         } 
  69.         return true
  70.     } 
  • equals()方法作为常用的方法,首先判断是否为同一个对象,再判断是否为要比较的类型,再判断两个对象的长度是否相等,首先从广的角度过滤筛选不符合的对象,再符合条件的对象基础上再一个一个字符的比较;
  • equalsIgnoreCase()方法是对equals()方法补充,不区分大小写的判断;
  • contentEquals()则是用于String对象与4种类型的判断,通常用于跟StringBuilder和StringBuffer的判断,也是对equals方法的一个补充;

8、regionMatchs()方法

  1. /** 
  2. * 这是一个类似于equals的方法,比较的是字符串的片段,也即是部分区域的比较 
  3. * toffset是当前字符串的比较起始位置(偏移量),other是要比较的String对象参数,ooffset是要参数String的比较片段起始位置,len是两个字符串要比较的片段的长度大小 
  4. */ 
  5. public boolean regionMatches(int toffset, String other, int ooffset, 
  6.             int len) { 
  7.         char ta[] = value;  //当前对象的值 
  8.         int to = toffset;   //当前对象的比较片段的起始位置,既偏移量 
  9.         char pa[] = other.value;  //参数,既比较字符串的值 
  10.         int po = ooffset;         //比较字符串的起始位置 
  11.         // Note: toffset, ooffset, or len might be near -1>>>1. 
  12.         if ((ooffset < 0) || (toffset < 0)  //起始位置不小于0或起始位置不大于字符串长度 - 片段长度,大于就截取不到这么长的片段了 
  13.                 || (toffset > (long)value.length - len) 
  14.                 || (ooffset > (long)other.value.length - len)) { 
  15.             return false;      //惊讶脸,居然不是抛异常,而是返回false 
  16.         } 
  17.         while (len-- > 0) {               //使用while循环,当然也可以使for循环 
  18.             if (ta[to++] != pa[po++]) {   //片段区域的字符元素逐个比较 
  19.                 return false
  20.             } 
  21.         } 
  22.         return true
  23.     } 
  1. /** 
  2. * 这个跟上面的方法一样,只不过多了一个参数,既ignoreCase,既是否为区分大小写。 
  3. * 是equalsIgnoreCase()方法的片段比较版本,实际上equalsIgnoreCase()也是调用regionMatches函数 
  4. */ 
  5.     public boolean regionMatches(boolean ignoreCase, int toffset, 
  6.             String other, int ooffset, int len) { 
  7.         char ta[] = value; 
  8.         int to = toffset; 
  9.         char pa[] = other.value; 
  10.         int po = ooffset; 
  11.         // Note: toffset, ooffset, or len might be near -1>>>1. 
  12.         if ((ooffset < 0) || (toffset < 0) 
  13.                 || (toffset > (long)value.length - len) 
  14.                 || (ooffset > (long)other.value.length - len)) { 
  15.             return false
  16.         } 
  17. //上面的解释同上 
  18.         while (len-- > 0) { 
  19.             char c1 = ta[to++]; 
  20.             char c2 = pa[po++]; 
  21.             if (c1 == c2) { 
  22.                 continue
  23.             } 
  24.             if (ignoreCase) {   //当ignoreCase为true时,既忽视大小写时 
  25.                 // If characters don't match but case may be ignored, 
  26.                 // try converting both characters to uppercase. 
  27.                 // If the results match, then the comparison scan should 
  28.                 // continue
  29.                 char u1 = Character.toUpperCase(c1);   //片段中每个字符转换为大写 
  30.                 char u2 = Character.toUpperCase(c2); 
  31.                 if (u1 == u2) { //大写比较一次,如果相等则不执行下面的语句,进入下一个循环 
  32.                     continue
  33.                 } 
  34.                 // Unfortunately, conversion to uppercase does not work properly 
  35.                 // for the Georgian alphabet, which has strange rules about case 
  36.                 // conversion.  So we need to make one last check before 
  37.                 // exiting. 
  38.                 if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) { 
  39.                  //每个字符换行成小写比较一次 
  40.                     continue
  41.                 } 
  42.             } 
  43.             return false
  44.         } 
  45.         return true
  46.     } 
  • 片段比较时针对String对象的;所以如果你要跟StringBuffer和StringBuilder比较,那么记得toString;
  • 如果你要进行两个字符串之间的片段比较的话,就可以使用regionMatches,如果是完整的比较那么就equals;

9、compareTo类函数和CaseInsensitiveComparator静态内部类

  1. /** 
  2. * 这是一个比较字符串中字符大小的函数,因为String实现了Comparable<String>接口,所以重写了compareTo方法 
  3. * Comparable是排序接口。若一个类实现了Comparable接口,就意味着该类支持排序。 
  4. * 实现了Comparable接口的类的对象的列表或数组可以通过Collections.sort或Arrays.sort进行自动排序。 
  5. *  
  6. * 参数是需要比较的另一个String对象 
  7. * 返回的int类型,正数为大,负数为小,是基于字符的ASSIC码比较的 
  8. *  
  9. */ 
  10. public int compareTo(String anotherString) { 
  11.         int len1 = value.length;                  //当前对象的长度 
  12.         int len2 = anotherString.value.length;    //比较对象的长度 
  13.         int lim = Math.min(len1, len2);           //获得最小长度 
  14.         char v1[] = value;                        //获得当前对象的值 
  15.         char v2[] = anotherString.value;          //获得比较对象的值 
  16.         int k = 0;                                //相当于forint k = 0,就是为while循环的数组服务的 
  17.         while (k < lim) {                         //当当前索引小于两个字符串中较短字符串的长度时,循环继续 
  18.             char c1 = v1[k];          //获得当前对象的字符 
  19.             char c2 = v2[k];          //获得比较对象的字符 
  20.             if (c1 != c2) {           //从前向后遍历,只要其实一个不相等,返回字符ASSIC的差值,int类型 
  21.                 return c1 - c2; 
  22.             } 
  23.             k++; 
  24.         } 
  25.         return len1 - len2;           //如果两个字符串同样位置的索引都相等,返回长度差值,完全相等则为0 
  26.     } 
  27. /** 
  28. *  这时一个类似compareTo功能的方法,但是不是comparable接口的方法,是String本身的方法 
  29. *  使用途径,我目前只知道可以用来不区分大小写的比较大小,但是不知道如何让它被工具类Collections和Arrays运用 
  30. */ 
  31. public int compareToIgnoreCase(String str) { 
  32.         return CASE_INSENSITIVE_ORDER.compare(this, str); 
  33.     } 
  34.     /** 
  35.     * 这是一个饿汉单例模式,是String类型的一个不区分大小写的比较器 
  36.     * 提供给Collections和Arrays的sort方法使用 
  37.     * 例如:Arrays.sort(strs,String.CASE_INSENSITIVE_ORDER); 
  38.     * 效果就是会将strs字符串数组中的字符串对象进行忽视大小写的排序 
  39.     * 
  40.     */ 
  41.     public static final Comparator<String> CASE_INSENSITIVE_ORDER 
  42.                                          = new CaseInsensitiveComparator(); 
  43. /** 
  44. * 这一个私有的静态内部类,只允许String类本身调用 
  45. * 实现了序列化接口和比较器接口,comparable接口和comparator是有区别的 
  46. * 重写了compare方法,该静态内部类实际就是一个String类的比较器 
  47. */ 
  48. private static class CaseInsensitiveComparator 
  49.             implements Comparator<String>, java.io.Serializable { 
  50.         // use serialVersionUID from JDK 1.2.2 for interoperability 
  51.         private static final long serialVersionUID = 8575799808933029326L; 
  52.         public int compare(String s1, String s2) { 
  53.             int n1 = s1.length();                 //s1字符串的长度 
  54.             int n2 = s2.length();                 //s2字符串的长度 
  55.             int min = Math.min(n1, n2);           //获得最小长度  
  56.             for (int i = 0; i < min; i++) { 
  57.                 char c1 = s1.charAt(i);           //逐一获得字符串i位置的字符 
  58.                 char c2 = s2.charAt(i); 
  59.                 if (c1 != c2) {                   //部分大小写比较一次 
  60.                     c1 = Character.toUpperCase(c1);    //转换大写比较一次 
  61.                     c2 = Character.toUpperCase(c2); 
  62.                     if (c1 != c2) { 
  63.                         c1 = Character.toLowerCase(c1);  //转换小写比较一次 
  64.                         c2 = Character.toLowerCase(c2); 
  65.                         if (c1 != c2) {                  //返回字符差值 
  66.                             // No overflow because of numeric promotion 
  67.                             return c1 - c2; 
  68.                         } 
  69.                     } 
  70.                 } 
  71.             } 
  72.             return n1 - n2;  //如果字符相等,但是长度不等,则返回长度差值,短的教小,所以小-大为负数 
  73.         } 
  74.         /** Replaces the de-serialized object. */ 
  75.         private Object readResolve() { return CASE_INSENSITIVE_ORDER; } 
  76.     } 
  • String实现了comparable接口,重写了compareTo方法,可以用于自己写类进行判断排序,也可以使用collections,Arrays工具类的sort进行排序。只有集合或数组中的元素实现了comparable接口,并重写了compareTo才能使用工具类排序;
  • CASE_INSENSITIVE_ORDER是一个单例,是String提供为外部的比较器,该比较器的作用是忽视大小写进行比较,我们可以通过Collections或Arrays的sort方法将CASE_INSENSITIVE_ORDER比较器作为参数传入,进行排序;

10、startWith、endWith类函数

  1. /** 
  2. * 作用就是当前对象[toffset,toffset + prefix.value.lenght]区间的字符串片段等于prefix 
  3. * 也可以说当前对象的toffset位置开始是否以prefix作为前缀 
  4. * prefix是需要判断的前缀字符串,toffset是当前对象的判断起始位置 
  5. */ 
  6.     public boolean startsWith(String prefix, int toffset) { 
  7.         char ta[] = value;     //获得当前对象的值 
  8.         int to = toffset;      //获得需要判断的起始位置,偏移量 
  9.         char pa[] = prefix.value; //获得前缀字符串的值 
  10.         int po = 0; 
  11.         int pc = prefix.value.length; 
  12.         // Note: toffset might be near -1>>>1. 
  13.         if ((toffset < 0) || (toffset > value.length - pc)) {  //偏移量不能小于0且能截取pc个长度 
  14.                     return false;  //不能则返回false 
  15.         } 
  16.         while (--pc >= 0) {                  //循环pc次,既prefix的长度 
  17.             if (ta[to++] != pa[po++]) {      //每次比较当前对象的字符串的字符是否跟prefix一样 
  18.                 return false;                //一样则pc--,to++,po++,有一个不同则返回false 
  19.             } 
  20.         } 
  21.         return true;  //没有不一样则返回true,当前对象是以prefix在toffset位置做为开头 
  22.     } 
  23. /** 
  24. * 判断当前字符串对象是否以字符串prefix起头 
  25. * 是返回true,否返回fasle 
  26. */ 
  27.     public boolean startsWith(String prefix) { 
  28.         return startsWith(prefix, 0); 
  29.     } 
  30. /** 
  31. * 判断当前字符串对象是否以字符串prefix结尾 
  32. * 是返回true,否返回fasle 
  33. */ 
  34.     public boolean endsWith(String suffix) { 
  35.     //suffix是需要判断是否为尾部的字符串。 
  36.     //value.length - suffix.value.length是suffix在当前对象的起始位置 
  37.         return startsWith(suffix, value.length - suffix.value.length);  
  38.     } 

endsWith的实现也是startWith(),作用就是判断前后缀;

11、hashCode()函数

  1. /** 
  2.    * 这是String字符串重写了Object类的hashCode方法。 
  3.    * 给由哈希表来实现的数据结构来使用,比如String对象要放入HashMap中。 
  4.    * 如果没有重写HashCode,或HaseCode质量很差则会导致严重的后果,既不靠谱的后果 
  5.    * 
  6.    */ 
  7.    public int hashCode() { 
  8.         int h = hash;  //hash是属性字段,是成员变量,所以默认为0 
  9.         if (h == 0 && value.length > 0) { //如果hash为0,且字符串对象长度大于0,不为"" 
  10.             char val[] = value;   //获得当前对象的值 
  11. //重点,String的哈希函数 
  12.             for (int i = 0; i < value.length; i++) {  //遍历len次 
  13.                 h = 31 * h + val[i];         //每次都是31 * 每次循环获得的h +第i个字符的ASSIC码 
  14.             } 
  15.             hash = h; 
  16.         } 
  17.         return h;  //由此可见""空字符对象的哈希值为0 
  18.     } 
  • hashCode的重点就是哈希函数;
  • String的哈希函数就是循环len次,每次循环体为 31 * 每次循环获得的hash + 第i次循环的字符;

12、indexOf、lastIndexOf类函数

  1. /** 
  2. * 返回cn对应的字符在字符串中第一次出现的位置,从字符串的索引0位置开始遍历 
  3. *  
  4. */ 
  5.     public int indexOf(int ch) { 
  6.         return indexOf(ch, 0); 
  7.     } 
  8. /** 
  9.  * index方法就是返回ch字符第一次在字符串中出现的位置 
  10.  * 既从fromIndex位置开始查找,从头向尾遍历,ch整数对应的字符在字符串中第一次出现的位置 
  11.  * -1代表字符串没有这个字符,整数代表字符第一次出现在字符串的位置 
  12.  */ 
  13.     public int indexOf(int ch, int fromIndex) { 
  14.         final int max = value.length; //获得字符串对象的长度 
  15.         if (fromIndex < 0) {             //如果偏移量小于0,则代表偏移量为0,校正偏移量 
  16.             fromIndex = 0; 
  17.         } else if (fromIndex >= max) {   //如果偏移量大于最大长度,则返回-1,代表没有字符串没有ch对应的字符 
  18.             // Note: fromIndex might be near -1>>>1. 
  19.             return -1; 
  20.         } 
  21.         if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) { //emmm,这个判断,不懂 
  22.             // handle most cases here (ch is a BMP code point or a 
  23.             // negative value (invalid code point)) 
  24.             final char[] value = this.value;             //获得字符串值 
  25.             for (int i = fromIndex; i < max; i++) {      //从fromIndex位置开始向后遍历 
  26.                 if (value[i] == ch) {                    //只有字符串中的某个位置的元素等于ch 
  27.                     return i;                            //返回对应的位置,函数结束,既第一次出现的位置 
  28.                 } 
  29.             } 
  30.             return -1;  //如果没有出现,则返回-1 
  31.         } else { 
  32.             return indexOfSupplementary(ch, fromIndex);  //emmm,紧紧接着没看懂的地方 
  33.         } 
  34.     } 
  35.     private int indexOfSupplementary(int ch, int fromIndex) { 
  36.         if (Character.isValidCodePoint(ch)) { 
  37.             final char[] value = this.value; 
  38.             final char hi = Character.highSurrogate(ch); 
  39.             final char lo = Character.lowSurrogate(ch); 
  40.             final int max = value.length - 1; 
  41.             for (int i = fromIndex; i < max; i++) { 
  42.                 if (value[i] == hi && value[i + 1] == lo) { 
  43.                     return i; 
  44.                 } 
  45.             } 
  46.         } 
  47.         return -1; 
  48.     } 
  49. /** 
  50. * 从尾部向头部遍历,返回cn第一次出现的位置,value.length - 1就是起点  
  51. * 为了理解,我们可以认为是返回cn对应的字符在字符串中最后出现的位置 
  52. *   
  53. * ch是字符对应的整数 
  54. */ 
  55.     public int lastIndexOf(int ch) { 
  56.         return lastIndexOf(ch, value.length - 1); 
  57.     } 
  58. /** 
  59. * 从尾部向头部遍历,从fromIndex开始作为起点,返回ch对应字符第一次在字符串出现的位置 
  60. * 既从头向尾遍历,返回cn对应字符在字符串中最后出现的一次位置,fromIndex为结束点 
  61. */ 
  62.     public int lastIndexOf(int ch, int fromIndex) { 
  63.         if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {  //之后不解释了,emmmmmmm 
  64.             // handle most cases here (ch is a BMP code point or a 
  65.             // negative value (invalid code point)) 
  66.             final char[] value = this.value; 
  67.             //取最小值,作用就是校正,如果fromIndex传大了,就当时len - 1 
  68.             int i = Math.min(fromIndex, value.length - 1);    
  69.             for (; i >= 0; i--) {      //算法中是从后向前遍历,直到i<0,退出循环 
  70.                 if (value[i] == ch) {  //只有有相等,返回对应的索引位置 
  71.                     return i; 
  72.                 } 
  73.             } 
  74.             return -1;   //没有找到则返回-1 
  75.         } else { 
  76.             return lastIndexOfSupplementary(ch, fromIndex); 
  77.         } 
  78.     } 
  79.     private int lastIndexOfSupplementary(int ch, int fromIndex) { 
  80.         if (Character.isValidCodePoint(ch)) { 
  81.             final char[] value = this.value; 
  82.             char hi = Character.highSurrogate(ch); 
  83.             char lo = Character.lowSurrogate(ch); 
  84.             int i = Math.min(fromIndex, value.length - 2); 
  85.             for (; i >= 0; i--) { 
  86.                 if (value[i] == hi && value[i + 1] == lo) { 
  87.                     return i; 
  88.                 } 
  89.             } 
  90.         } 
  91.         return -1; 
  92.     } 
  93. /** 
  94. * 返回第一次出现的字符串的位置 
  95. */ 
  96.     public int indexOf(String str) { 
  97.         return indexOf(str, 0); 
  98.     } 
  99. /** 
  100. * 从fromIndex开始遍历,返回第一次出现str字符串的位置 
  101. */ 
  102.     public int indexOf(String str, int fromIndex) { 
  103.         return indexOf(value, 0, value.length, 
  104.                 str.value, 0, str.value.length, fromIndex); 
  105.     } 
  106. /** 
  107. * 这是一个不对外公开的静态函数 
  108. * source就是原始字符串,sourceOffset就是原始字符串的偏移量,起始位置。 
  109. * sourceCount就是原始字符串的长度,target就是要查找的字符串。 
  110. * fromIndex就是从原始字符串的第fromIndex开始遍历 
  111. */ 
  112.     static int indexOf(char[] source, int sourceOffset, int sourceCount, 
  113.             String target, int fromIndex) { 
  114.         return indexOf(source, sourceOffset, sourceCount, 
  115.                        target.value, 0, target.value.length, 
  116.                        fromIndex); 
  117.     } 
  118. /** 
  119. * 同是一个不对外公开的静态函数 
  120. * 比上更为强大。 
  121. * 多了一个targetOffset和targetCount,既代表别查找的字符串也可以被切割 
  122. */ 
  123.     static int indexOf(char[] source, int sourceOffset, int sourceCount, 
  124.             char[] target, int targetOffset, int targetCount, 
  125.             int fromIndex) { 
  126.         if (fromIndex >= sourceCount) {   //如果查找的起点大于当前对象的大小 
  127.         //如果目标字符串的长度为0,则代表目标字符串为""""在任何字符串都会出现 
  128.         //配合fromIndex >= sourceCount,所以校正第一次出现在最尾部,仅仅是校正作用 
  129.             return (targetCount == 0 ? sourceCount : -1);  
  130.         } 
  131.         if (fromIndex < 0) {  //也是校正,如果起始点小于0,则返回0 
  132.             fromIndex = 0; 
  133.         } 
  134.         if (targetCount == 0) { //如果目标字符串长度为0,代表为"",则第一次出现在遍历起始点fromIndex 
  135.             return fromIndex; 
  136.         } 
  137.         char first = target[targetOffset];   //目标字符串的第一个字符 
  138.         int max = sourceOffset + (sourceCount - targetCount); //最大遍历次数 
  139.         for (int i = sourceOffset + fromIndex; i <= max; i++) { 
  140.             /* Look for first character. */ 
  141.             if (source[i] != first) { 
  142.                 while (++i <= max && source[i] != first); 
  143.             } 
  144.             /* Found first character, now look at the rest of v2 */ 
  145.             if (i <= max) { 
  146.                 int j = i + 1; 
  147.                 int end = j + targetCount - 1; 
  148.                 for (int k = targetOffset + 1; j < end && source[j] 
  149.                         == target[k]; j++, k++); 
  150.                 if (j == end) { 
  151.                     /* Found whole string. */ 
  152.                     return i - sourceOffset; 
  153.                 } 
  154.             } 
  155.         } 
  156.         return -1; 
  157.     } 
  158. /** 
  159. * 查找字符串Str最后一次出现的位置 
  160. */ 
  161.     public int lastIndexOf(String str) { 
  162.         return lastIndexOf(str, value.length); 
  163.     } 
  164.     public int lastIndexOf(String str, int fromIndex) { 
  165.         return lastIndexOf(value, 0, value.length, 
  166.                 str.value, 0, str.value.length, fromIndex); 
  167.     } 
  168.     static int lastIndexOf(char[] source, int sourceOffset, int sourceCount, 
  169.             String target, int fromIndex) { 
  170.         return lastIndexOf(source, sourceOffset, sourceCount, 
  171.                        target.value, 0, target.value.length, 
  172.                        fromIndex); 
  173.     } 
  174.     static int lastIndexOf(char[] source, int sourceOffset, int sourceCount, 
  175.             char[] target, int targetOffset, int targetCount, 
  176.             int fromIndex) { 
  177.         /* 
  178.          * Check arguments; return immediately where possible. For 
  179.          * consistency, don't check for null str. 
  180.          */ 
  181.         int rightIndex = sourceCount - targetCount; 
  182.         if (fromIndex < 0) { 
  183.             return -1; 
  184.         } 
  185.         if (fromIndex > rightIndex) { 
  186.             fromIndex = rightIndex; 
  187.         } 
  188.         /* Empty string always matches. */ 
  189.         if (targetCount == 0) { 
  190.             return fromIndex; 
  191.         } 
  192.         int strLastIndex = targetOffset + targetCount - 1; 
  193.         char strLastChar = target[strLastIndex]; 
  194.         int min = sourceOffset + targetCount - 1; 
  195.         int i = min + fromIndex; 
  196.     startSearchForLastChar: 
  197.         while (true) { 
  198.             while (i >= min && source[i] != strLastChar) { 
  199.                 i--; 
  200.             } 
  201.             if (i < min) { 
  202.                 return -1; 
  203.             } 
  204.             int j = i - 1; 
  205.             int start = j - (targetCount - 1); 
  206.             int k = strLastIndex - 1; 
  207.             while (j > start) { 
  208.                 if (source[j--] != target[k--]) { 
  209.                     i--; 
  210.                     continue startSearchForLastChar; 
  211.                 } 
  212.             } 
  213.             return start - sourceOffset + 1; 
  214.         } 
  215.     } 

只对外提供了int整形,String字符串两种参数的重载方法;

13、substring()函数

  1. /** 
  2. *  截取当前字符串对象的片段,组成一个新的字符串对象 
  3. *  beginIndex为截取的初始位置,默认截到len - 1位置 
  4. */ 
  5. public String substring(int beginIndex) { 
  6.         if (beginIndex < 0) {   //小于0抛异常 
  7.             throw new StringIndexOutOfBoundsException(beginIndex); 
  8.         } 
  9.         int subLen = value.length - beginIndex;  //新字符串的长度 
  10.         if (subLen < 0) {       //小于0抛异常 
  11.             throw new StringIndexOutOfBoundsException(subLen); 
  12.         } 
  13.         //如果beginIndex是0,则不用截取,返回自己(非新对象),否则截取0到subLen位置,不包括(subLen) 
  14.         return (beginIndex == 0) ? this : new String(value, beginIndex, subLen); 
  15.     } 
  1. /** 
  2. * 截取一个区间范围 
  3. * [beginIndex,endIndex),不包括endIndex 
  4. */ 
  5.     public String substring(int beginIndex, int endIndex) { 
  6.         if (beginIndex < 0) { 
  7.             throw new StringIndexOutOfBoundsException(beginIndex); 
  8.         } 
  9.         if (endIndex > value.length) { 
  10.             throw new StringIndexOutOfBoundsException(endIndex); 
  11.         } 
  12.         int subLen = endIndex - beginIndex; 
  13.         if (subLen < 0) { 
  14.             throw new StringIndexOutOfBoundsException(subLen); 
  15.         } 
  16.         return ((beginIndex == 0) && (endIndex == value.length)) ? this 
  17.                 : new String(value, beginIndex, subLen); 
  18.     } 
  19.     public CharSequence subSequence(int beginIndex, int endIndex) { 
  20.         return this.substring(beginIndex, endIndex); 
  21.     } 
  • substring函数是一个不完全闭包的区间,是[beginIndex,end),不包括end位置;
  • subString的原理是通过String的构造函数实现的;

14、concat()函数

  1. /** 
  2. * String的拼接函数 
  3. * 例如:String  str = "abc"; str.concat("def")    output"abcdef" 
  4. */ 
  5. public String concat(String str) { 
  6.         int otherLen = str.length();//获得参数字符串的长度 
  7.         if (otherLen == 0) { //如果长度为0,则代表不需要拼接,因为str为"" 
  8.             return this; 
  9.         } 
  10. /****重点****/ 
  11.         int len = value.length;  //获得当前对象的长度  
  12.         //将数组扩容,将value数组拷贝到buf数组中,长度为len + str.lenght 
  13.         char buf[] = Arrays.copyOf(value, len + otherLen);  
  14.         str.getChars(buf, len); //然后将str字符串从buf字符数组的len位置开始覆盖,得到一个完整的buf字符数组 
  15.         return new String(buf, true);//构建新的String对象,调用私有的String构造方法 
  16.     } 

15、replace、replaceAll类函数

//替换,将字符串中的oldChar字符全部替换成newChar

  1. public String replace(char oldChar, char newChar) { 
  2.         if (oldChar != newChar) {    //如果旧字符不等于新字符的情况下 
  3.             int len = value.length;  //获得字符串长度 
  4.             int i = -1;              //flag 
  5.             char[] val = value; /* avoid getfield opcode */ 
  6.             while (++i < len) {      //循环len次 
  7.                 if (val[i] == oldChar) { //找到第一个旧字符,打断循环 
  8.                     break; 
  9.                 } 
  10.             } 
  11.             if (i < len) {   //如果第一个旧字符的位置小于len 
  12.                 char buf[] = new char[len]; 新new一个字符数组,len个长度 
  13.                 for (int j = 0; j < i; j++) { 
  14.                     buf[j] = val[j];        把旧字符的前面的字符都复制到新字符数组上 
  15.                 } 
  16.                 while (i < len) {           //从i位置开始遍历 
  17.                     char c = val[i]; 
  18.                     buf[i] = (c == oldChar) ? newChar : c; //发生旧字符就替换,不想关的则直接复制 
  19.                     i++; 
  20.                 } 
  21.                 return new String(buf, true);  //通过新字符数组buf重构一个新String对象 
  22.             } 
  23.         } 
  24.         return this;  //如果old = new ,直接返回自己 
  25.     } 
  26. //替换第一个旧字符 
  27. String replaceFirst(String regex, String replacement) { 
  28.         return Pattern.compile(regex).matcher(this).replaceFirst(replacement); 
  29.     } 
  30. //当不是正规表达式时,与replace效果一样,都是全体换。如果字符串的正则表达式,则规矩表达式全体替换 
  31.     public String replaceAll(String regex, String replacement) { 
  32.         return Pattern.compile(regex).matcher(this).replaceAll(replacement); 
  33.     } 
  34. //可以用旧字符串去替换新字符串 
  35.     public String replace(CharSequence target, CharSequence replacement) { 
  36.         return Pattern.compile(target.toString(), Pattern.LITERAL).matcher( 
  37.                 this).replaceAll(Matcher.quoteReplacement(replacement.toString())); 
  38.     } 

从replace的算法中,我们可以发现,它不是从头开始遍历替换的,而是首先找到第一个要替换的字符,从要替换的字符开始遍历,发现一个替换一个;

16、matches()和contains()函数;

  1. /** 
  2. * matches() 方法用于检测字符串是否匹配给定的正则表达式。 
  3. * regex -- 匹配字符串的正则表达式。 
  4. * 如:String Str = new String("www.snailmann.com"); 
  5. * System.out.println(Str.matches("(.*)snailmann(.*)"));   output:true 
  6. * System.out.println(Str.matches("www(.*)"));             output:true 
  7. */ 
  8. public boolean matches(String regex) { 
  9.         return Pattern.matches(regex, this);   //实际使用的是Pattern.matches()方法 
  10.     } 
  11. //是否含有CharSequence这个子类元素,通常用于StrngBuffer,StringBuilder 
  12.     public boolean contains(CharSequence s) { 
  13.         return indexOf(s.toString()) > -1; 
  14.     } 

17、split()函

  1. public String[] split(String regex, int limit) { 
  2.         /* fastpath if the regex is a 
  3.          (1)one-char String and this character is not one of the 
  4.             RegEx's meta characters ".$|()[{^?*+\\"or 
  5.          (2)two-char String and the first char is the backslash and 
  6.             the second is not the ascii digit or ascii letter. 
  7.          */ 
  8.         char ch = 0; 
  9.         if (((regex.value.length == 1 && 
  10.              ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) || 
  11.              (regex.length() == 2 && 
  12.               regex.charAt(0) == '\\' && 
  13.               (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 && 
  14.               ((ch-'a')|('z'-ch)) < 0 && 
  15.               ((ch-'A')|('Z'-ch)) < 0)) && 
  16.             (ch < Character.MIN_HIGH_SURROGATE || 
  17.              ch > Character.MAX_LOW_SURROGATE)) 
  18.         { 
  19.             int off = 0; 
  20.             int next = 0; 
  21.             boolean limited = limit > 0; 
  22.             ArrayList<String> list = new ArrayList<>(); 
  23.             while ((next = indexOf(ch, off)) != -1) { 
  24.                 if (!limited || list.size() < limit - 1) { 
  25.                     list.add(substring(offnext)); 
  26.                     off = next + 1; 
  27.                 } else {    // last one 
  28.                     //assert (list.size() == limit - 1); 
  29.                     list.add(substring(off, value.length)); 
  30.                     off = value.length; 
  31.                     break; 
  32.                 } 
  33.             } 
  34.             // If no match was found, return this 
  35.             if (off == 0) 
  36.                 return new String[]{this}; 
  37.             // Add remaining segment 
  38.             if (!limited || list.size() < limit) 
  39.                 list.add(substring(off, value.length)); 
  40.             // Construct result 
  41.             int resultSize = list.size(); 
  42.             if (limit == 0) { 
  43.                 while (resultSize > 0 && list.get(resultSize - 1).length() == 0) { 
  44.                     resultSize--; 
  45.                 } 
  46.             } 
  47.             String[] result = new String[resultSize]; 
  48.             return list.subList(0, resultSize).toArray(result); 
  49.         } 
  50.         return Pattern.compile(regex).split(this, limit); 
  51.     } 
  52.     public String[] split(String regex) { 
  53.         return split(regex, 0); 
  54.     } 

18、join()函数

  1. /** 
  2.   * join方法是JDK1.8加入的新函数,静态方法 
  3.   * 这个方法就是跟split有些对立的函数,不过join是静态方法 
  4.   * delimiter就是分割符,后面就是要追加的可变参数,比如str1,str2,str3 
  5.   *  
  6.   * 例子:String.join(",",new String("a"),new String("b"),new String("c")) 
  7.   * output"a,b,c" 
  8.   */ 
  9.   public static String join(CharSequence delimiter, CharSequence... elements) { 
  10.         Objects.requireNonNull(delimiter);  //就是检测是否为Null,是null,抛异常 
  11.         Objects.requireNonNull(elements);   //不是就返回自己,即nothing happen 
  12.         // Number of elements not likely worth Arrays.stream overhead. 
  13.         StringJoiner joiner = new StringJoiner(delimiter);  //嗯,有兴趣自己看StringJoiner类源码啦 
  14.         for (CharSequence cs: elements) { 
  15.             joiner.add(cs);   //既用分割符delimiter将所有可变参数的字符串分割,合并成一个字符串 
  16.         } 
  17.         return joiner.toString(); 
  18.     } 
  1. /** 
  2.    * 功能是一样的,不过传入的参数不同 
  3.    * 这里第二个参数一般就是装着CharSequence子类的集合 
  4.    * 比如String.join(",",lists)    
  5.    * list可以是一个Collection接口实现类,所含元素的基类必须是CharSequence类型 
  6.    * 比如String,StringBuilder,StringBuffer等 
  7.    */  
  8.    public static String join(CharSequence delimiter, 
  9.             Iterable<? extends CharSequence> elements) { 
  10.         Objects.requireNonNull(delimiter); 
  11.         Objects.requireNonNull(elements); 
  12.         StringJoiner joiner = new StringJoiner(delimiter); 
  13.         for (CharSequence cs: elements) { 
  14.             joiner.add(cs); 
  15.         } 
  16.         return joiner.toString(); 
  17.     } 
  • Java 1.8加入的新功能,有点跟split对立的意思,是个静态方法;
  • 有两个重载方法,一个是直接传字符串数组,另个是传集合。传集合的方式是一个好功能,很方遍将集合的字符串元素拼接成一个字符串;

19、trim()函数

  1. /** 
  2. * 去除字符串首尾部分的空值,如,' ' or " ",非"" 
  3. * 原理是通过substring去实现的,首尾各一个指针 
  4. * 头指针发现空值就++,尾指针发现空值就-- 
  5. ' 'Int值为32,其实不仅仅是去空的作用,应该是整数值小于等于32的去除掉 
  6. */ 
  7.    public String trim() { 
  8.         int len = value.length; //代表尾指针,实际是尾指针+1的大小 
  9. int st = 0;             //代表头指针 
  10.         char[] val = value;    /* avoid getfield opcode */ 
  11. //st<len,且字符的整数值小于32则代表有空值,st++ 
  12.         while ((st < len) && (val[st] <= ' ')) {    
  13.             st++; 
  14.         } 
  15.     //len - 1才是真正的尾指针,如果尾部元素的整数值<=32,则代表有空值,len-- 
  16.         while ((st < len) && (val[len - 1] <= ' ')) { 
  17.             len--; 
  18.         } 
  19.         //截取st到len的字符串(不包括len位置) 
  20.         return ((st > 0) || (len < value.length)) ? substring(st, len) : this; 
  21.     } 

常见去首尾的空值,实际是去除首尾凡是小于32的字符;

20、toString()函数

  1. //就是返回自己 
  2.  public String toString() { 
  3.         return this; 
  4.  } 

21、toCharArray()函数

  1. /** 
  2. * 就是将String转换为字符数组并返回 
  3. */ 
  4.  public char[] toCharArray() { 
  5.         // Cannot use Arrays.copyOf because of class initialization order issues 
  6.         char result[] = new char[value.length];     //定义一个要返回的空数组,长度为字符串长度 
  7.         System.arraycopy(value, 0, result, 0, value.length); //拷贝 
  8.         return result; //返回 
  9.  } 

22、toLowerCase()、toUpperCase()函数

  1. //en,好长,下次再更新吧,先用着吧 
  2. public String toLowerCase(Locale locale) { 
  3.         if (locale == null) { 
  4.             throw new NullPointerException(); 
  5.         } 
  6.         int firstUpper; 
  7.         final int len = value.length; 
  8.         /* Now check if there are any characters that need to be changed. */ 
  9.         scan: { 
  10.             for (firstUpper = 0 ; firstUpper < len; ) { 
  11.                 char c = value[firstUpper]; 
  12.                 if ((c >= Character.MIN_HIGH_SURROGATE) 
  13.                         && (c <= Character.MAX_HIGH_SURROGATE)) { 
  14.                     int supplChar = codePointAt(firstUpper); 
  15.                     if (supplChar != Character.toLowerCase(supplChar)) { 
  16.                         break scan; 
  17.                     } 
  18.                     firstUpper += Character.charCount(supplChar); 
  19.                 } else { 
  20.                     if (c != Character.toLowerCase(c)) { 
  21.                         break scan; 
  22.                     } 
  23.                     firstUpper++; 
  24.                 } 
  25.             } 
  26.             return this; 
  27.         } 
  28.         char[] result = new char[len]; 
  29.         int resultOffset = 0;  /* result may grow, so i+resultOffset 
  30.                                 * is the write location in result */ 
  31.         /* Just copy the first few lowerCase characters. */ 
  32.         System.arraycopy(value, 0, result, 0, firstUpper); 
  33.         String lang = locale.getLanguage(); 
  34.         boolean localeDependent = 
  35.                 (lang == "tr" || lang == "az" || lang == "lt"); 
  36.         char[] lowerCharArray; 
  37.         int lowerChar; 
  38.         int srcChar; 
  39.         int srcCount; 
  40.         for (int i = firstUpper; i < len; i += srcCount) { 
  41.             srcChar = (int)value[i]; 
  42.             if ((char)srcChar >= Character.MIN_HIGH_SURROGATE 
  43.                     && (char)srcChar <= Character.MAX_HIGH_SURROGATE) { 
  44.                 srcChar = codePointAt(i); 
  45.                 srcCount = Character.charCount(srcChar); 
  46.             } else { 
  47.                 srcCount = 1; 
  48.             } 
  49.             if (localeDependent || 
  50.                 srcChar == '\u03A3' || // GREEK CAPITAL LETTER SIGMA 
  51.                 srcChar == '\u0130') { // LATIN CAPITAL LETTER I WITH DOT ABOVE 
  52.                 lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale); 
  53.             } else { 
  54.                 lowerChar = Character.toLowerCase(srcChar); 
  55.             } 
  56.             if ((lowerChar == Character.ERROR) 
  57.                     || (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) { 
  58.                 if (lowerChar == Character.ERROR) { 
  59.                     lowerCharArray = 
  60.                             ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale); 
  61.                 } else if (srcCount == 2) { 
  62.                     resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount; 
  63.                     continue
  64.                 } else { 
  65.                     lowerCharArray = Character.toChars(lowerChar); 
  66.                 } 
  67.                 /* Grow result if needed */ 
  68.                 int mapLen = lowerCharArray.length; 
  69.                 if (mapLen > srcCount) { 
  70.                     char[] result2 = new char[result.length + mapLen - srcCount]; 
  71.                     System.arraycopy(result, 0, result2, 0, i + resultOffset); 
  72.                     result = result2; 
  73.                 } 
  74.                 for (int x = 0; x < mapLen; ++x) { 
  75.                     result[i + resultOffset + x] = lowerCharArray[x]; 
  76.                 } 
  77.                 resultOffset += (mapLen - srcCount); 
  78.             } else { 
  79.                 result[i + resultOffset] = (char)lowerChar; 
  80.             } 
  81.         } 
  82.         return new String(result, 0, len + resultOffset); 
  83.     } 
  84.     public String toLowerCase() { 
  85.         return toLowerCase(Locale.getDefault()); 
  86.     } 
  87.     public String toUpperCase(Locale locale) { 
  88.         if (locale == null) { 
  89.             throw new NullPointerException(); 
  90.         } 
  91.         int firstLower; 
  92.         final int len = value.length; 
  93.         /* Now check if there are any characters that need to be changed. */ 
  94.         scan: { 
  95.             for (firstLower = 0 ; firstLower < len; ) { 
  96.                 int c = (int)value[firstLower]; 
  97.                 int srcCount; 
  98.                 if ((c >= Character.MIN_HIGH_SURROGATE) 
  99.                         && (c <= Character.MAX_HIGH_SURROGATE)) { 
  100.                     c = codePointAt(firstLower); 
  101.                     srcCount = Character.charCount(c); 
  102.                 } else { 
  103.                     srcCount = 1; 
  104.                 } 
  105.                 int upperCaseChar = Character.toUpperCaseEx(c); 
  106.                 if ((upperCaseChar == Character.ERROR) 
  107.                         || (c != upperCaseChar)) { 
  108.                     break scan; 
  109.                 } 
  110.                 firstLower += srcCount; 
  111.             } 
  112.             return this; 
  113.         } 
  114.         /* result may grow, so i+resultOffset is the write location in result */ 
  115.         int resultOffset = 0; 
  116.         char[] result = new char[len]; /* may grow */ 
  117.         /* Just copy the first few upperCase characters. */ 
  118.         System.arraycopy(value, 0, result, 0, firstLower); 
  119.         String lang = locale.getLanguage(); 
  120.         boolean localeDependent = 
  121.                 (lang == "tr" || lang == "az" || lang == "lt"); 
  122.         char[] upperCharArray; 
  123.         int upperChar; 
  124.         int srcChar; 
  125.         int srcCount; 
  126.         for (int i = firstLower; i < len; i += srcCount) { 
  127.             srcChar = (int)value[i]; 
  128.             if ((char)srcChar >= Character.MIN_HIGH_SURROGATE && 
  129.                 (char)srcChar <= Character.MAX_HIGH_SURROGATE) { 
  130.                 srcChar = codePointAt(i); 
  131.                 srcCount = Character.charCount(srcChar); 
  132.             } else { 
  133.                 srcCount = 1; 
  134.             } 
  135.             if (localeDependent) { 
  136.                 upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale); 
  137.             } else { 
  138.                 upperChar = Character.toUpperCaseEx(srcChar); 
  139.             } 
  140.             if ((upperChar == Character.ERROR) 
  141.                     || (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) { 
  142.                 if (upperChar == Character.ERROR) { 
  143.                     if (localeDependent) { 
  144.                         upperCharArray = 
  145.                                 ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale); 
  146.                     } else { 
  147.                         upperCharArray = Character.toUpperCaseCharArray(srcChar); 
  148.                     } 
  149.                 } else if (srcCount == 2) { 
  150.                     resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount; 
  151.                     continue
  152.                 } else { 
  153.                     upperCharArray = Character.toChars(upperChar); 
  154.                 } 
  155.                 /* Grow result if needed */ 
  156.                 int mapLen = upperCharArray.length; 
  157.                 if (mapLen > srcCount) { 
  158.                     char[] result2 = new char[result.length + mapLen - srcCount]; 
  159.                     System.arraycopy(result, 0, result2, 0, i + resultOffset); 
  160.                     result = result2; 
  161.                 } 
  162.                 for (int x = 0; x < mapLen; ++x) { 
  163.                     result[i + resultOffset + x] = upperCharArray[x]; 
  164.                 } 
  165.                 resultOffset += (mapLen - srcCount); 
  166.             } else { 
  167.                 result[i + resultOffset] = (char)upperChar; 
  168.             } 
  169.         } 
  170.         return new String(result, 0, len + resultOffset); 
  171.     } 
  172.     public String toUpperCase() { 
  173.         return toUpperCase(Locale.getDefault()); 
  174.     } 

二、String 为什么是不可变的

  • String 不可变是因为在 JDK 中 String 类被声明为一个 final 类,且类内部的 value 字节数组也是 final 的,只有当字符串是不可变时字符串池才有可能实现,字符串池的实现可以在运行时节约很多 heap 空间,因为不同的字符串变量都指向池中的同一个字符串;
  • 如果字符串是可变的则会引起很严重的安全问题,譬如数据库的用户名密码都是以字符串的形式传入来获得数据库的连接,或者在 socket 编程中主机名和端口都是以字符串的形式传入,因为字符串是不可变的,所以它的值是不可改变的,否则黑客们可以钻到空子改变字符串指向的对象的值造成安全漏洞;
  • 因为字符串是不可变的,所以是多线程安全的,同一个字符串实例可以被多个线程共享,这样便不用因为线程安全问题而使用同步,字符串自己便是线程安全的;
  • 因为字符串是不可变的所以在它创建的时候 hashcode 就被缓存了,不变性也保证了 hash 码的唯一性,不需要重新计算,这就使得字符串很适合作为 Map 的键,字符串的处理速度要快过其它的键对象,这就是 HashMap 中的键往往都使用字符串的原因;

总结

 

StringBuffer、StringBuilder和String一样,也用来代表字符串。String类是不可变类,任何对String的改变都 会引发新的String对象的生成;StringBuilder则是可变类,任何对它所指代的字符串的改变都不会产生新的对象,而StringBuilder则是线程安全版的StringBuilder;

 

责任编辑:武晓燕 来源: Android开发编程
相关推荐

2021-09-02 07:00:01

Glide流程Android

2021-09-07 06:40:25

AndroidLiveData原理

2021-08-10 20:41:33

AndroidApp流程

2021-09-01 06:48:16

AndroidGlide缓存

2021-09-13 15:17:52

FastThreadL源码Java

2021-08-17 13:41:11

AndroidView事件

2021-10-29 08:19:54

JMeterJava java sample

2021-09-03 07:27:38

AndroidGlide管理

2021-08-05 20:39:34

AndroidKotlinStandard.kt

2021-09-05 07:35:58

lifecycleAndroid组件原理

2021-08-25 07:43:17

AndroidSurfaceViewTextureView

2011-07-18 16:36:15

syslogLinux日志管理

2021-09-18 06:56:01

JavaCAS机制

2021-09-09 06:55:43

AndroidViewDragHel原理

2021-09-11 07:32:15

Java线程线程池

2010-10-19 14:48:09

Java String

2011-06-23 14:27:48

QT QLibrary 动态库

2011-06-23 13:10:39

Python 对象机制

2021-02-05 11:27:09

微服务源码加载配置

2020-08-26 14:00:37

C++string语言
点赞
收藏

51CTO技术栈公众号