Java String Chomp chompLast(String str, String sep)

Here you can find the source of chompLast(String str, String sep)

Description

Remove a value if and only if the String ends with that value.

License

Apache License

Parameter

Parameter Description
str the String to chomp from, must not be null
sep the String to chomp, must not be null

Exception

Parameter Description
NullPointerException if str or sep is <code>null</code>

Return

String without chomped ending

Declaration

public static String chompLast(String str, String sep) 

Method Source Code

//package com.java2s;
/**/*  ww w  .  j  a va 2s  .  c o  m*/
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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
 */

public class Main {
    /**
     * <p>Remove a value if and only if the String ends with that value.</p>
     *
     * @param str  the String to chomp from, must not be null
     * @param sep  the String to chomp, must not be null
     * @return String without chomped ending
     * @throws NullPointerException if str or sep is <code>null</code>
     */
    public static String chompLast(String str, String sep) {
        if (str.length() == 0) {
            return str;
        }
        String sub = str.substring(str.length() - sep.length());
        if (sep.equals(sub)) {
            return str.substring(0, str.length() - sep.length());
        }
        return str;
    }
}

Related

  1. chomp(StringBuilder sb)
  2. chompAllAndTrim(String str)
  3. chompClosureOpen(String expr)
  4. chompHeader(String str, String prex)
  5. chompLast(String str)
  6. chompNewLine(String line)