Java String remove from start

Description

Java String remove from start


//package com.demo2s;

public class Main {
  public static void main(String[] argv) throws Exception {
    String str = "demo2s.com";
    String remove = "demo";
    System.out.println(removeStart(str, remove));
  }/*w  ww  .  ja  va2 s .  com*/

  /**
   * The empty String <code>""</code>.
   * 
   * @since 2.0
   */
  public static final String EMPTY = "";

  /**
   * <p>
   * Removes a substring only if it is at the begining of a source string,
   * otherwise returns 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> search
   * string will return the source string.
   * </p>
   *
   * <pre>
   * removeStart(null, *)      = null
   * removeStart("", *)        = ""
   * removeStart(*, null)      = *
   * removeStart("www.domain.com", "www.")   = "domain.com"
   * removeStart("domain.com", "www.")       = "domain.com"
   * removeStart("www.domain.com", "domain") = "www.domain.com"
   * removeStart("abc", "")    = "abc"
   * </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 removeStart(String str, String remove) {
    if (isEmpty(str) || isEmpty(remove)) {
      return str;
    }
    if (str.startsWith(remove)) {
      return str.substring(remove.length());
    }
    return str;
  }

  /**
   * <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