Java String remove substring

Description

Java String remove substring


//package com.demo2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String str = "demo2s.com test test test";
        String oldchars = "t";
        System.out.println(removeChars(str, oldchars));
    }//  ww  w . ja  v a  2  s  .c  om

    /**
     * Remove any occurrances of 'oldchars' in 'str'.
     * Example: removeChars("Hello, world!", ",!") returns "Hello world"
     */
    public static String removeChars(String str, String oldchars) {
        int pos = indexOfChars(str, oldchars);
        if (pos == -1) {
            return str;
        }

        StringBuilder buf = new StringBuilder();
        int start = 0;
        do {
            buf.append(str.substring(start, pos));
            start = pos + 1;
            pos = indexOfChars(str, oldchars, start);
        } while (pos != -1);

        if (start < str.length()) {
            buf.append(str.substring(start));
        }
        return buf.toString();
    }

    /**
     * Like String.indexOf() except that it will look for any of the
     * characters in 'chars' (similar to C's strpbrk)
     */
    public static int indexOfChars(String str, String chars, int fromIndex) {
        final int len = str.length();

        for (int pos = fromIndex; pos < len; pos++) {
            if (chars.indexOf(str.charAt(pos)) >= 0) {
                return pos;
            }
        }

        return -1;
    }

    /**
     * Like String.indexOf() except that it will look for any of the
     * characters in 'chars' (similar to C's strpbrk)
     */
    public static int indexOfChars(String str, String chars) {
        return indexOfChars(str, chars, 0);
    }
}
public class Main {
  public static void main(String[] argv) throws Exception {
    String str = "demo2s.com demo2s.com demo2s.com";
    String remove = "com";
    System.out.println(remove(str, remove));
  }/*from   w w  w .  j ava  2 s  .  c om*/

  /**
   * <p>
   * Removes all occurrences of a substring from within the source string.
   * </p>
   *
   * <p>
   * A <code>null</code> source string will return <code>null</code>. An empty
   * ("") source string will return the empty string. A <code>null</code> remove
   * string will return the source string. An empty ("") remove string will return
   * the source string.
   * </p>
   *
   * <pre>
   * remove(null, *)        = null
   * remove("", *)          = ""
   * remove(*, null)        = *
   * remove(*, "")          = *
   * remove("queued", "ue") = "qd"
   * remove("queued", "zz") = "queued"
   * </pre>
   *
   * @param str
   *          the source String to search, may be null
   * @param remove
   *          the String to search for and remove, may be null
   * @return the substring with the string removed if found, <code>null</code> if
   *         null String input
   * @since 2.1
   */
  public static String remove(String str, String remove) {
    if (isEmpty(str) || isEmpty(remove)) {
      return str;
    }
    return replace(str, remove, "", -1);
  }

  /**
   * <p>
   * Replaces a String with another String inside a larger String, for the first
   * <code>max</code> values of the search String.
   * </p>
   *
   * <p>
   * A <code>null</code> reference passed to this method is a no-op.
   * </p>
   *
   * <pre>
   * replace(null, *, *, *)         = null
   * replace("", *, *, *)           = ""
   * replace("any", null, *, *)     = "any"
   * replace("any", *, null, *)     = "any"
   * replace("any", "", *, *)       = "any"
   * replace("any", *, *, 0)        = "any"
   * replace("abaa", "a", null, -1) = "abaa"
   * replace("abaa", "a", "", -1)   = "b"
   * replace("abaa", "a", "z", 0)   = "abaa"
   * replace("abaa", "a", "z", 1)   = "zbaa"
   * replace("abaa", "a", "z", 2)   = "zbza"
   * replace("abaa", "a", "z", -1)  = "zbzz"
   * </pre>
   *
   * @param text
   *          text to search and replace in, may be null
   * @param searchString
   *          the String to search for, may be null
   * @param replacement
   *          the String to replace it with, may be null
   * @param max
   *          maximum number of values to replace, or <code>-1</code> if no
   *          maximum
   * @return the text with any replacements processed, <code>null</code> if null
   *         String input
   */
  public static String replace(String text, String searchString, String replacement, int max) {
    if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) {
      return text;
    }
    int start = 0;
    int end = text.indexOf(searchString, start);
    if (end == -1) {
      return text;
    }
    int replLength = searchString.length();
    int increase = replacement.length() - replLength;
    increase = (increase < 0 ? 0 : increase);
    increase *= (max < 0 ? 16 : (max > 64 ? 64 : max));
    StringBuffer buf = new StringBuffer(text.length() + increase);
    while (end != -1) {
      buf.append(text.substring(start, end)).append(replacement);
      start = end + replLength;
      if (--max == 0) {
        break;
      }
      end = text.indexOf(searchString, start);
    }
    buf.append(text.substring(start));
    return buf.toString();
  }

  public static boolean isEmpty(String str) {
    return str == null || str.length() == 0;
  }
}

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */



PreviousNext

Related