Java实现rtrim功能,批量删除字符串指定末尾的字符串
public static String removeEndLoop(String str, String remove) { if (StringUtils.isBlank(str) || StringUtils.isBlank(remove)) { return str; } if (!str.endsWith(remove)) { return str; } final StringBuilder sb = new StringBuilder(str); for (int lastIndex = sb.length(), removeLen = remove.length(); lastIndex >= 0; ) { lastIndex = str.lastIndexOf(remove, lastIndex - 1); /******************************************************************************** * lastIndex == -1 目的是为了处理所有字符串都是都是与末尾的字符串一致时候除法 * lastIndex != sb.length() - removeLen 为了防止当前删除字符串中间里面存在的末尾字符串 ********************************************************************************/ if (lastIndex == -1 || lastIndex != sb.length() - removeLen) { break; } sb.delete(lastIndex, sb.length()); } return sb.toString(); } public static void main(String[] args) { String str0 = "============"; String str1 = "abcdefg=csfsg==efsdf===sdfs========"; String str2 = "sdfsdfabcsdfsdfabcsdfsdabcabcabc"; final String str0Result = removeEndLoop(str0, "="); log.info("str0原字符串为:{}", str0); log.info("得到的str0的最后结果为:{}", str0Result); log.info("=================================================="); final String str1Result = removeEndLoop(str1, "="); log.info("str1原字符串为:{}", str1); log.info("得到的str1的最后结果为:{}", str1Result); log.info("=================================================="); final String str2Result = removeEndLoop(str2, "abc"); log.info("str2原字符串为:{}", str2); log.info("得到的str2的最后结果为:{}", str2Result); log.info("=================================================="); }