jdk/src/java.base/share/classes/java/lang/String.java
changeset 30913 bb5c454d451e
parent 30642 d9891f85d583
child 31671 362e0c0acece
equal deleted inserted replaced
30912:5c720b6875a2 30913:bb5c454d451e
  2245      * @param  replacement The replacement sequence of char values
  2245      * @param  replacement The replacement sequence of char values
  2246      * @return  The resulting string
  2246      * @return  The resulting string
  2247      * @since 1.5
  2247      * @since 1.5
  2248      */
  2248      */
  2249     public String replace(CharSequence target, CharSequence replacement) {
  2249     public String replace(CharSequence target, CharSequence replacement) {
  2250         return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
  2250         String starget = target.toString();
  2251                 this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
  2251         String srepl = replacement.toString();
       
  2252         int j = indexOf(starget);
       
  2253         if (j < 0) {
       
  2254             return this;
       
  2255         }
       
  2256         int targLen = starget.length();
       
  2257         int targLen1 = Math.max(targLen, 1);
       
  2258         final char[] value = this.value;
       
  2259         final char[] replValue = srepl.value;
       
  2260         int newLenHint = value.length - targLen + replValue.length;
       
  2261         if (newLenHint < 0) {
       
  2262             throw new OutOfMemoryError();
       
  2263         }
       
  2264         StringBuilder sb = new StringBuilder(newLenHint);
       
  2265         int i = 0;
       
  2266         do {
       
  2267             sb.append(value, i, j - i)
       
  2268                     .append(replValue);
       
  2269             i = j + targLen;
       
  2270         } while (j < value.length && (j = indexOf(starget, j + targLen1)) > 0);
       
  2271 
       
  2272         return sb.append(value, i, value.length - i).toString();
  2252     }
  2273     }
  2253 
  2274 
  2254     /**
  2275     /**
  2255      * Splits this string around matches of the given
  2276      * Splits this string around matches of the given
  2256      * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
  2277      * <a href="../util/regex/Pattern.html#sum">regular expression</a>.