KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > columba > core > base > TextUtil


1 package org.columba.core.base;
2
3 /**
4  * Text utilities.
5  *
6  * @author Frederik Dietz
7  */

8 public class TextUtil {
9
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 JavaDoc replaceAll(final String JavaDoc inputString,
19             final String JavaDoc oldPattern, final String JavaDoc newPattern) {
20         
21         if (oldPattern.equals("")) { //$NON-NLS-1$
22
throw new IllegalArgumentException JavaDoc("Old pattern must have content."); //$NON-NLS-1$
23
}
24
25         final StringBuffer JavaDoc result = new StringBuffer JavaDoc();
26         // startIdx and idxOld delimit various chunks of aInput; these
27
// chunks always end where aOldPattern begins
28
int startIdx = 0;
29         int idxOld = 0;
30         while ((idxOld = inputString.indexOf(oldPattern, startIdx)) >= 0) {
31             // grab a part of aInput which does not include aOldPattern
32
result.append(inputString.substring(startIdx, idxOld));
33             // add aNewPattern to take place of aOldPattern
34
result.append(newPattern);
35
36             // reset the startIdx to just after the current match, to see
37
// if there are any further matches
38
startIdx = idxOld + oldPattern.length();
39         }
40         // the final chunk will go to the end of aInput
41
result.append(inputString.substring(startIdx));
42         return result.toString();
43     }
44 }
45
Popular Tags