简体   繁体   English

如何不使用StringBuilder从字符串(而不是数组)中删除重复项?

[英]How to remove duplicates from string (not array) without using StringBuilder?

I am working with my program and I need to remove repeated characters from a string given to me by the user. 我正在使用我的程序,我需要从用户给我的字符串中删除重复的字符。 I referenced other questions, but they are all using StringBuilder to remove duplicates. 我引用了其他问题,但是它们都使用StringBuilder删除重复项。 However, is there any way to remove duplicates without turning the string into an array, using StringBuilder and Set ? 但是,有没有什么方法可以使用StringBuilderSet删除重复项而不将字符串转换为数组?

I haven't learnt those yet, so I don't understand them very well. 我还没有学过,所以我不太了解它们。 Could I get some help? 我可以帮忙吗?

For example, if user types in happyrolling the result should be hapyroling . 例如,如果用户键入happyrolling则结果应为hapyroling

It seems from your example you want to remove repeated characters (not words ). 从您的示例看来,您想要删除重复的字符 (而不是word )。

You can use regex to find the repeats and remove them: 您可以使用正则表达式找到重复项并将其删除:

str = str.replaceAll("(.)\\1+", "$1");

This regex captures every character but only matches when followed by the same character by using a back reference to the captured group. 此正则表达式捕获每个字符,但仅在后面有相同字​​符时才使用对捕获的组的反向引用进行匹配。 The replacement is the captured character, so for example "xx" is replaced by "x" 替换是捕获的字符,因此例如“ xx”被替换为“ x”

Somehow you need to convert the string into character array. 您需要以某种方式将字符串转换为字符数组。 String is immutable in Java, so if you want to do any type of operation in the String, either you have to convert it to charArray or you have to use StringBuilder to create new String. String在Java中是不可变的,因此,如果要在String中执行任何类型的操作,则必须将其转换为charArray,或者必须使用StringBuilder创建新的String。 You can keep track of the used character using hashmap. 您可以使用哈希图跟踪使用的字符。

public String removeDuplicates(String str){
    char[] array = str.toCharArray();
    char ch;
    int k = 0;
    HashMap<Character, Integer> hMap = new HashMap();
    for(int i = 0; i < str.length(); i++){
        ch = array[i];
        if(hMap.get(ch) == null){
            array[k++] = ch;
            hMap.put(ch, 1);
        }
    }
    return new String(array, 0, k);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM