Java String remove char

Description

Java String remove char

public class Main {
  public static void main(String[] argv) throws Exception {
    String str = "demo2s.com";
    char remove = 'd';
    System.out.println(remove(str, remove));
  }// w w  w  . j a v a  2 s.c  om
  /**
   * <p>
   * Removes all occurrences of a character 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.
   * </p>
   *
   * <pre>
   * remove(null, *)       = null
   * remove("", *)         = ""
   * remove("queued", 'u') = "qeed"
   * remove("queued", 'z') = "queued"
   * </pre>
   *
   * @param str
   *          the source String to search, may be null
   * @param remove
   *          the char to search for and remove, may be null
   * @return the substring with the char removed if found, <code>null</code> if
   *         null String input
   * @since 2.1
   */
  public static String remove(String str, char remove) {
    if (isEmpty(str) || str.indexOf(remove) == -1) {
      return str;
    }
    char[] chars = str.toCharArray();
    int pos = 0;
    for (int i = 0; i < chars.length; i++) {
      if (chars[i] != remove) {
        chars[pos++] = chars[i];
      }
    }
    return new String(chars, 0, pos);
  }

  /**
   * <p>
   * Checks if a String is empty ("") or null.
   * </p>
   *
   * <pre>
   * isEmpty(null)      = true
   * isEmpty("")        = true
   * isEmpty(" ")       = false
   * isEmpty("bob")     = false
   * isEmpty("  bob  ") = false
   * </pre>
   *
   * <p>
   * NOTE: This method changed in Lang version 2.0. It no longer trims the String.
   * That functionality is available in isBlank().
   * </p>
   *
   * @param str
   *          the String to check, may be null
   * @return <code>true</code> if the String is empty or null
   */
  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