删除特定字符

本文介绍了一种使用自定义Hash表实现从源字符串中移除指定字符的方法。通过遍历待减少的字符并将其存入Hash表,再遍历输入字符串以移除已记录的字符,最终返回不含这些字符的新字符串。

主要是如何构造hash表。


public class DeleteChar {

	public String delete(String input, String reduce) throws Exception{
		assert(true);
		char[] s = input.toCharArray();
		char[] r = reduce.toCharArray();
		HashMap map = new HashMap();
		for(char c : r){
			map.put(c);
		}
		StringBuffer sb = new StringBuffer();
		for(char c : s){
			int i = map.get(c);
			if(i == 0){
				sb.append(c);
			}
		}
		return sb.toString();
	}

	
	private class HashMap{
		private int[] a = new int[128];
		
		public void put(char c) throws Exception{
			if(c<0 || c>127){
				throw new Exception();
			}
			if(a[c] != 1){
				a[c] = 1;
			}
		}
		
		public int get(char c) throws Exception{
			if(c<0 || c>127){
				throw new Exception();
			}
			return a[c];
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		DeleteChar o = new DeleteChar();
		String s = null;
		try {
			s = o.delete("I am a student.", ".aasse");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println(s);
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值