View Javadoc

1   ////////////////////////////////////////////////////////////////////////////////
2   // MillScript: an Open Spice interpreter and batch website creation tool
3   // Copyright (C) 2005 Kevin Rogers
4   //
5   // This file is part of MillScript.
6   //
7   // MillScript is free software; you can redistribute it and/or modify it under
8   // the terms of the GNU General Public License as published by the Free
9   // Software Foundation; either version 2 of the License, or (at your option)
10  // any later version.
11  //
12  // MillScript is distributed in the hope that it will be useful, but WITHOUT
13  // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  // FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
15  // more details.
16  //
17  // You should have received a copy of the GNU General Public License along with
18  // MillScript; if not, write to the Free Software Foundation, Inc., 59 Temple
19  // Place, Suite 330, Boston, MA  02111-1307  USA
20  ////////////////////////////////////////////////////////////////////////////////
21  package org.millscript.millscript.tools;
22  
23  /**
24   * This is a utility class containing basic String related methods.
25   */
26  public final class StringTools {
27  
28      /**
29       * Hidden constructor.
30       */
31      private StringTools() {
32      }
33  
34      /**
35       * Returns the source string with all occurrances of the pattern string
36       * substituted with the replacement string.
37       *
38       * @param src   the source string
39       * @param pat   the pattern string
40       * @param rep   the replacement string
41       * @return  the source string with all occurances of the pattern
42       * substituted with the replacement
43       */
44      public static final String substituteAll( final String src, final String pat, final String rep ) {
45          final int plen = pat.length();
46          final int slen = src.length();
47          final StringBuffer r = new StringBuffer( src.length() * 2 );
48          int a = 0;
49          for (;;) {
50              int b = src.indexOf( pat, a );
51              if ( b == -1 ) {
52                  if ( a == 0 ) {
53                      return src;
54                  }
55                  for ( int i = a; i < slen; i++ ) {
56                      r.append( src.charAt( i ) );
57                  }
58                  return r.toString();
59              }
60              for ( int i = a; i < b; i++ ) {
61                  r.append( src.charAt( i ) );
62              }
63              r.append( rep );
64              a = b + plen;
65          }
66      }
67  
68  }