为了账号安全,请及时绑定邮箱和手机立即绑定

java去除字符串中重复、不重复、消除重复后字符

标签:
Java


java去除字符串中重复、不重复、消除重复后字符

import java.util.HashSet;

import java.util.Set;

public class Main {

public static void main(String[] args) {

    String str = "aaasd";

    System.out.println("原字符串: "+str);

    Set<Character> set1 = new HashSet<Character>();

    Set<Character> set2 = new HashSet<Character>();

    Set<Character> set3 = new HashSet<Character>();

    //把字符串转为字符数组

    char[] cs = str.toCharArray();

    //便利字符数组aaasd

    for(char c:cs){

        //把遍历的字符加入set1(HashSet,无序不可重复)

        boolean b = set1.add(c);//asd

        if(!b){

            //b不为true就是有重复的字符,重复的字符加入set2

            set2.add(c);//a

        }

    }

    //把消除重复后的字符set1赋给Set3

    set3.addAll(set1);//asd

    //把消除的重复后的字符set1 - 重复的字符set2 = 不重复的字符

    set3.removeAll(set2);//asd-a = sd

    System.out.println("=========消除重复厚的字符=========");

    for ( char c : set1){

        System.out.print(c + "");

    }

    System.out.println("\n===========重复的字符===============");

    for (char c :set2){

        System.out.print(c + "");

    }

    System.out.println("\n========不重复的数组===========");

    for (char c :set3){

        System.out.print(c + "");

    }

}

}

©著作权归作者所有:来自51CTO博客作者1ceMan7的原创作品,如需转载,请注明出处,否则将追究法律责任


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消