删除一个字符串中指定的多个字符的算法
源码出处:org.springframework.util.StringUtils#deleteAny
/**
* Delete any character in a given {@code String}.
* @param inString the original {@code String}
* @param charsToDelete a set of characters to delete.
* E.g. "az\n" will delete 'a's, 'z's and new lines.
* @return the resulting {@code String}
*/
public static String deleteAny(String inString, @Nullable String charsToDelete) {
if (!hasLength(inString) || !hasLength(charsToDelete)) {
return inString;
}
int lastCharIndex = 0;
// 新建一个结果字符数组
char[] result = new char[inString.length()];
// 遍历字符串
for (int i = 0; i < inString.length(); i++) {
// 取出每个字符
char c = inString.charAt(i);
// 判断字符是否在要删除字符里面
if (charsToDelete.indexOf(c) == -1) {
// 不是删除字符,把字符放入结果字符数组
result[lastCharIndex++] = c;
}
}
if (lastCharIndex == inString.length()) {
return inString;
}
return new String(result, 0, lastCharIndex);
}
demo
import org.springframework.util.StringUtils;
public class DeleteAnyCharsTest {
public static void main(String[] args) {
String test = "123z\n%d%s%SS";
String charsToDelete = "\n%z";
// 输出123dsSS
System.out.println(StringUtils.deleteAny(test, charsToDelete));
}
}