Java String remove from end
//package com.demo2s; public class Main { public static void main(String[] argv) throws Exception { String str = "demo2s.com"; String remove = "com"; System.out.println(removeEnd(str, remove)); }//w w w .java 2s .c o m /** * The empty String <code>""</code>. * @since 2.0 */ public static final String EMPTY = ""; /** * <p>Removes a substring only if it is at the end 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> * removeEnd(null, *) = null * removeEnd("", *) = "" * removeEnd(*, null) = * * removeEnd("www.domain.com", ".com.") = "www.domain.com" * removeEnd("www.domain.com", ".com") = "www.domain" * removeEnd("www.domain.com", "domain") = "www.domain.com" * removeEnd("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 removeEnd(String str, String remove) { if (isEmpty(str) || isEmpty(remove)) { return str; } if (str.endsWith(remove)) { return str.substring(0, str.length() - 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. */