Closed lilanlong closed 1 month ago
我先合并,不过计算会产生很多的arry copy,我做了改进:
/**
* 去掉指定所有前缀,如:
* <pre>{@code
* str=abcdef, prefix=ab => return cdef
* str=ababcdef, prefix=ab => return cdef
* str=ababcdef, prefix="" => return ababcdef
* str=ababcdef, prefix=null => return ababcdef
* }</pre>
*
* @param str 字符串,空返回原字符串
* @param prefix 前缀,空返回原字符串
* @return 去掉所有前缀的字符串,若前缀不是 preffix, 返回原字符串
*/
public static String removeAllPrefix(final CharSequence str, final CharSequence prefix) {
if (isEmpty(str) || isEmpty(prefix)) {
return toStringOrNull(str);
}
final String prefixStr = prefix.toString();
final int prefixLength = prefixStr.length();
final String str2 = str.toString();
int toIndex = 0;
while (str2.startsWith(prefixStr, toIndex)) {
toIndex += prefixLength;
}
return subSuf(str2, toIndex);
}
/**
* 去掉指定所有后缀,如:
* <pre>{@code
* str=11abab, suffix=ab => return 11
* str=11ab, suffix=ab => return 11
* str=11ab, suffix="" => return 11ab
* str=11ab, suffix=null => return 11ab
* }</pre>
*
* @param str 字符串,空返回原字符串
* @param suffix 后缀字符串,空返回原字符串
* @return 去掉所有后缀的字符串,若后缀不是 suffix, 返回原字符串
*/
public static String removeAllSuffix(final CharSequence str, final CharSequence suffix) {
if (isEmpty(str) || isEmpty(suffix)) {
return toStringOrNull(str);
}
final String suffixStr = suffix.toString();
final int suffixLength = suffixStr.length();
final String str2 = str.toString();
int toIndex = str2.length();
while (str2.startsWith(suffixStr, toIndex - suffixLength)){
toIndex -= suffixLength;
}
return subPre(str2, toIndex);
}
增加移除所有前缀方法:removeAllPrefix 增加移除所有后缀方法:removeAllSuffix