字符串去重

1.经典版:
将字符串“我我我我我我我..........我........要要要要要.............要要
要要....学习习习......习习习习习习习习习编程程程程程程程程程程程.....程程程程程程程程” ----> "我要学习编程"
思路:创建字符串储存这一串字符,创建集合(根据题意认真筛选),见字符串转型成字符数组,用for循环对他的每一个字符
进行遍历,里面添加条件(去重+除点),并且将其添加到创建的集合中,然后我们再对集合进行遍历;
点击查看代码
import java.util.ArrayList;
public class Demo1 {
    public static void main(String[] args) {
        String s = "我我我我我我我..........我........要要要要要.............要要要要....学习习习......习习习习习习习习习编程程程程程程程程程程程.....程程程程程程程程";
        char[] chars = s.toCharArray();
        ArrayList<Character> list = new ArrayList<>();
        for (int i = 0; i < chars.length; i++) {
            if(!list.contains(chars[i])  && chars[i] != '.'){

                list.add(chars[i]);
            }
        }
        for (Character character : list) {
            System.out.print(character);
        }

    }

}

我们将题目稍微做一下更改
将字符串“bbbbb......ccc,d,ddd.....aaaa....abcd..dbddaaggg...,,,211....23567898765432..13579...2468.987654”==>123456789abcdg
点击查看代码
import java.util.TreeSet;
public class Demo5 {
    public static void main(String[] args) {
        String s = "bbbbb......ccc,d,ddd.....aaaa....abcd..dbddaaggg...,,,211....23567898765432..13579...2468.987654";
        char[] chars = s.toCharArray();
        TreeSet<Character> set = new TreeSet<>();//可以对字符进行排序
        for (int i = 0; i < s.length(); i++) {
            if(!set.contains(chars[i]) && chars[i]!='.'&&chars[i]!=','){
                set.add(chars[i]);
            }
        }
        for (Character c : set) {
            System.out.print(c);
        }
    }
}

posted @ 2024-10-23 14:43  wang_jun  阅读(79)  评论(0)    收藏  举报