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