StringUtil.java
上传用户:qing5858
上传日期:2015-10-27
资源大小:6056k
文件大小:2k
源码类别:

搜索引擎

开发平台:

Java

  1. package net.javacoding.jspider.core.util;
  2. /**
  3.  * Utility class that allows for easy string manipulation.  This class will be
  4.  * deprecated once the support for JDK 1.3 will no longer be given, as the
  5.  * functionality delivered by this class is incorporated out-of-the box in
  6.  * Java 1.4 (String class, replace methods, etc ...)
  7.  *
  8.  * $Id: StringUtil.java,v 1.3 2003/05/02 17:36:59 vanrogu Exp $
  9.  *
  10.  * @author G黱ther Van Roey ( gunther@javacoding.net )
  11.  */
  12. public class StringUtil {
  13.     /**
  14.      * Replaces the occurences of a certain pattern in a string with a replacement
  15.      * String.
  16.      * @param string the string to be inspected
  17.      * @param pattern the string pattern to be replaced
  18.      * @param replacement the string that should go where the pattern was
  19.      * @return the string with the replacements done
  20.      */
  21.     public static String replace ( String string, String pattern, String replacement ) {
  22.         String replaced = null;
  23.         if (string == null) {
  24.             replaced = null;
  25.         } else if (pattern == null || pattern.length() == 0 ) {
  26.             replaced = string;
  27.         } else {
  28.             StringBuffer sb = new StringBuffer();
  29.             int lastIndex = 0;
  30.             int index = string.indexOf(pattern);
  31.             while (index >= 0) {
  32.                 sb.append(string.substring(lastIndex, index));
  33.                 sb.append(replacement);
  34.                 lastIndex = index + pattern.length();
  35.                 index = string.indexOf(pattern, lastIndex);
  36.             }
  37.             sb.append(string.substring(lastIndex));
  38.             replaced = sb.toString();
  39.         }
  40.         return replaced;
  41.     }
  42.     /**
  43.      * @todo add Junit tests for this one
  44.      */
  45.     public static String replace  ( String string, String pattern, String replacement, int start ) {
  46.         String begin = string.substring(0, start);
  47.         String end = string.substring(start);
  48.         return begin + replace(end, pattern, replacement );
  49.     }
  50. }