String中查询重复字符

论坛 期权论坛 脚本     
匿名技术用户   2020-12-23 17:25   11   0
@Test
public void test1() {
    String str = "aaaaddaaddababacaxaxcccaswfdsfasgdfah";
    //把SIZE提前取出,免得在循环中每次都得取
    int charSize = str.length();
    Set<Object> rSet = new HashSet<>();
    for (int j = 1; j <= charSize; j++) {
        for (int i = 0; i < charSize; i++) {
            String strE2 = null;
            if (i < charSize - j) {
                //截取的波动区间为(1~SIZE-1)
                strE2 = str.substring(i, i + j);
                System.out.println( "---" + strE2 + "---" );
                //正向查找,反向查找,如果能查到则返回对应的位置
                //因为是从str中截取的strE2,所以不会有indexOf()==-1的情况
                int indexS = str.indexOf(strE2);
                int indexE = str.lastIndexOf(strE2);
                    if(indexS != indexE){
                        //使用Set的特性过滤并保存重复的值
                        rSet.add(strE2);
                    }
                }
            }
        }
        System.out.println(rSet);
    }
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP