1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | package Torello.Java; import Torello.Java.Function.IntTFunction; import Torello.Java.StringParse; class StrArrToReplFunc { static String replace( final boolean ignoreCase, final String s, final String[] matchStrs, final IntTFunction<String, String> replaceFunction ) { // Loop simply checks for null pointers. for (int i=0; i < matchStrs.length; i++) if (matchStrs[i] == null) throw new NullPointerException( "The " + i + StringParse.ordinalIndicator(i) + " of array parameter " + "'matchStrs' is null." ); // Use a StringBuilder to build the return String. It is precisely what it was // it was designed for. StringBuilder sb = new StringBuilder(); int last = 0; // Main Loop: Builds a replacement StringBuilder. Looks for matches between the input // String 's', and the matchStrs in array String[] matchStrs. TOP: for (int i=0; i < s.length(); i++) for (int j=0; j < matchStrs.length; j++) if (s.regionMatches(ignoreCase, i, matchStrs[j], 0, matchStrs[j].length())) { // A match was found, so begin String nonMatchStr = s.substring(last, i); String oldStr = s.substring(i, i + matchStrs[j].length()); String newStr = replaceFunction.apply(i, oldStr); // Append them to the StringBuilder. if (nonMatchStr.length() > 0) sb.append(nonMatchStr); sb.append(newStr); // Update the pointers last = i + oldStr.length(); i = last - 1; // use -1 because of the loop-incrementer at top continue TOP; } if (last == 0) return s; // There were no matches, return original String. // This happens when there are remaining characters after the last match that occurred. // Same as the HTML Parser - trailing READ/PARSE. if (last < s.length()) sb.append(s.substring(last)); return sb.toString(); } } |