01: package org.columba.core.base;
02:
03: /**
04: * Text utilities.
05: *
06: * @author Frederik Dietz
07: */
08: public class TextUtil {
09:
10: /**
11: * Replace all occurences of <code>oldPattern</code> with <code>newPattern</code>
12: *
13: * @param inputString input string
14: * @param oldPattern old pattern
15: * @param newPattern new pattern
16: * @return new string
17: */
18: public static String replaceAll(final String inputString,
19: final String oldPattern, final String newPattern) {
20:
21: if (oldPattern.equals("")) { //$NON-NLS-1$
22: throw new IllegalArgumentException(
23: "Old pattern must have content."); //$NON-NLS-1$
24: }
25:
26: final StringBuffer result = new StringBuffer();
27: // startIdx and idxOld delimit various chunks of aInput; these
28: // chunks always end where aOldPattern begins
29: int startIdx = 0;
30: int idxOld = 0;
31: while ((idxOld = inputString.indexOf(oldPattern, startIdx)) >= 0) {
32: // grab a part of aInput which does not include aOldPattern
33: result.append(inputString.substring(startIdx, idxOld));
34: // add aNewPattern to take place of aOldPattern
35: result.append(newPattern);
36:
37: // reset the startIdx to just after the current match, to see
38: // if there are any further matches
39: startIdx = idxOld + oldPattern.length();
40: }
41: // the final chunk will go to the end of aInput
42: result.append(inputString.substring(startIdx));
43: return result.toString();
44: }
45: }
|