JavaHashset字符串练习

第四题:HashSet的应用
编写程序,给定字符串,如:
String str = “abaacdebbafblmbffnoeeepawc”;
输出其中重复的字符、不重复的字符以及消除重复以后的字符列表。
比如:
原字符串:abaacdebbafblmbffnoeeepawc
消除重复后的字符====
p a b c d e f w l m n o
重复的字符====
a b c e f
不重复的字符====
p d w l m n o

import java.util.HashSet;
import java.util.Set;

public class Main {
	public static void main(String[] args) {
		String str = "abaacdebbafblmbffnoeeepawc";
		Set<Character> s = new HashSet<Character>();//用来记录去重的字符
		Set<Character> s1 = new HashSet<Character>();//用来记录重复的字符
		Set<Character> s2 = new HashSet<Character>();//用来记录不重复的字符
		char  ch[] = str.toCharArray();
		for(char c : ch) {
			boolean b = s.add(c);
			if(!b) {
				s1.add(c);
			}
		}
		s2.addAll(s);//去重后的字符串
		s2.removeAll(s1);//再去掉重复的字符串
		//去重后的字符串
		System.out.println("原字符串:"+str);
		System.out.println("====消除重复后的字符========");
		for(char c :s) {
			System.out.print(c+" ");
		}
		System.out.println();
		System.out.println("====重复的字符========");
		for(char c :s1) {
			System.out.print(c+" ");
		}
		System.out.println();
		System.out.println("====不重复的字符========");
		for(char c :s2) {
			System.out.print(c+" ");
		}
	}
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值