删除一个字符串中指定的多个字符的算法

删除一个字符串中指定的多个字符的算法
源码出处: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));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值