KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > javacoding > jspider > core > util > StringUtil


1 package net.javacoding.jspider.core.util;
2
3
4 /**
5  * Utility class that allows for easy string manipulation. This class will be
6  * deprecated once the support for JDK 1.3 will no longer be given, as the
7  * functionality delivered by this class is incorporated out-of-the box in
8  * Java 1.4 (String class, replace methods, etc ...)
9  *
10  * $Id: StringUtil.java,v 1.3 2003/05/02 17:36:59 vanrogu Exp $
11  *
12  * @author Günther Van Roey ( gunther@javacoding.net )
13  */

14 public class StringUtil {
15
16     /**
17      * Replaces the occurences of a certain pattern in a string with a replacement
18      * String.
19      * @param string the string to be inspected
20      * @param pattern the string pattern to be replaced
21      * @param replacement the string that should go where the pattern was
22      * @return the string with the replacements done
23      */

24     public static String JavaDoc replace ( String JavaDoc string, String JavaDoc pattern, String JavaDoc replacement ) {
25         String JavaDoc replaced = null;
26
27         if (string == null) {
28             replaced = null;
29         } else if (pattern == null || pattern.length() == 0 ) {
30             replaced = string;
31         } else {
32
33             StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
34
35             int lastIndex = 0;
36             int index = string.indexOf(pattern);
37             while (index >= 0) {
38                 sb.append(string.substring(lastIndex, index));
39                 sb.append(replacement);
40                 lastIndex = index + pattern.length();
41                 index = string.indexOf(pattern, lastIndex);
42             }
43             sb.append(string.substring(lastIndex));
44             replaced = sb.toString();
45         }
46         return replaced;
47     }
48
49     /**
50      * @todo add Junit tests for this one
51      */

52     public static String JavaDoc replace ( String JavaDoc string, String JavaDoc pattern, String JavaDoc replacement, int start ) {
53         String JavaDoc begin = string.substring(0, start);
54         String JavaDoc end = string.substring(start);
55         return begin + replace(end, pattern, replacement );
56     }
57 }
58
Popular Tags