001package io.ebean.enhance.ant;
002
003
004/**
005 * Utility String class that supports String manipulation functions.
006 */
007public class StringReplace {
008
009  /**
010   * This method takes a String and will replace all occurrences of the match
011   * String with that of the replace String.
012   *
013   * @param source  the source string
014   * @param match   the string used to find a match
015   * @param replace the string used to replace match with
016   * @return the source string after the search and replace
017   */
018  public static String replace(String source, String match, String replace) {
019    return replaceString(source, match, replace, 30, 0, source.length());
020  }
021
022  /**
023   * Additionally specify the additionalSize to add to the buffer. This will
024   * make the buffer bigger so that it doesn't have to grow when replacement
025   * occurs.
026   */
027  private static String replaceString(String source, String match, String replace,
028                                      int additionalSize, int startPos, int endPos) {
029
030    char match0 = match.charAt(0);
031
032    int matchLength = match.length();
033
034    if (matchLength == 1 && replace.length() == 1) {
035      char replace0 = replace.charAt(0);
036      return source.replace(match0, replace0);
037    }
038    if (matchLength >= replace.length()) {
039      additionalSize = 0;
040    }
041
042
043    int sourceLength = source.length();
044    int lastMatch = endPos - matchLength;
045
046    StringBuilder sb = new StringBuilder(sourceLength + additionalSize);
047
048    if (startPos > 0) {
049      sb.append(source, 0, startPos);
050    }
051
052    char sourceChar;
053    boolean isMatch;
054    int sourceMatchPos;
055
056    for (int i = startPos; i < sourceLength; i++) {
057      sourceChar = source.charAt(i);
058      if (i > lastMatch || sourceChar != match0) {
059        sb.append(sourceChar);
060
061      } else {
062        // check to see if this is a match
063        isMatch = true;
064        sourceMatchPos = i;
065
066        // check each following character...
067        for (int j = 1; j < matchLength; j++) {
068          sourceMatchPos++;
069          if (source.charAt(sourceMatchPos) != match.charAt(j)) {
070            isMatch = false;
071            break;
072          }
073        }
074        if (isMatch) {
075          i = i + matchLength - 1;
076          sb.append(replace);
077        } else {
078          // was not a match
079          sb.append(sourceChar);
080        }
081      }
082    }
083
084    return sb.toString();
085  }
086
087
088}