Removing duplicate characters in a String (user in

2019-09-04 11:51发布

private String removeDuplicates(String userKeyword){
    int wordLength = userKeyword.length();
    int lengthCounter;
    for (lengthCounter=0; lengthCounter<wordLength; lengthCounter++){
        if (userKeyword.charAt(lengthCounter) != userKeyword.charAt(lengthCounter + 1)){
            String revisedKeyword = "" + userKeyword.charAt(lengthCounter);
            userKeyword = revisedKeyword;
        } 
    }
    return userKeyword;
}

I'm really new to java. We haven't used String builders, Strung buffer, Arrays, etc yet.... We haven't even gotten to loops, but I figured it will be the easiest way to use... Please help.

8条回答
干净又极端
2楼-- · 2019-09-04 12:19

Following are my two favorite ways to remove duplicated chars in String:

The first one doesn't use StringBuffer or StringBuilder. Only using contains().

private static String removeDup(String str){
    String result = new String("");

    for (int i = 0; i < str.length(); i++) {
        if (!result.contains("" + str.charAt(i))) {
            result += "" + str.charAt(i);
        }
    }

    return result;
}

And if StringBuffer or StringBuilder is allowed, the code may become even cleaner and simpler. Here is my second way that uses StringBuilder.

private static String removeDup(String str){
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i<str.length();i++){
        String si = str.substring(i, i+1);
        if (sb.indexOf(si)==-1){
            sb.append (si);
        }
    }
    return sb.toString();
}

Of course, using set to implement this function is also a good solution. Kon has done a great job in this thread.

查看更多
smile是对你的礼貌
3楼-- · 2019-09-04 12:24
public static void main(String[] args) 

    {
        String stringWithDuplicates = "sathishssathish";
        char[] charecters = stringWithDuplicates.toCharArray();
        boolean[] duplicateFound = new boolean[130];
        StringBuilder sb = new StringBuilder();
        for (char c : charecters) {
            if (!duplicateFound[c]) {
                duplicateFound[c] = true;
                sb.append(c);
            }
        }
        System.out.println("SubString.main()" + sb);
    }
查看更多
放我归山
4楼-- · 2019-09-04 12:29

Let's keep it clean and simple. The following code will check and make sure character held at .charAt(char c) is not found on the result String.

public static void main(String[] args)
{
    String input = "ABCADEDBF";
    String result = delDuplicate(input);
    System.out.println(result);
}


public static String delDuplicate(final String str)
{
    String result = "";

    for (int i = 0; i < str.length(); i++)
        if (!result.contains(str.charAt(i) + ""))
            result += str.charAt(i);

    return result;
}
查看更多
手持菜刀,她持情操
5楼-- · 2019-09-04 12:29

A simple solution would be

public class duplicate

{
  public static void main(String args[])
   {
     String a= "stackoverflow";
     char c[]=a.toCharArray();
     int l=a.length();
     String b="";
     for(int i=0;i<l;i++)
       {
            if(b.contains(""+c[i]))
            {   
            }
            else
            {
                b=b+""+c[i];
            }
        }


    System.out.println(b);

    }

}
查看更多
beautiful°
6楼-- · 2019-09-04 12:32

There are infinitely many ways to do this. Finding your own solution within the bounds of the toolset you've established is what learning to program is all about. Here is one possible solution to get you thinking:

Create a Set, which by default can only hold unique values

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

Then loop over the characters in your String, adding each to mySet

mySet.add(c);

When you're done, your set will have a list of characters that are unique and in order, you can print them out with

for (char c : mySet) {
    System.out.println(c)
}

EDIT:

Here is a simple set up using nested loops

String s = "einstein"; //This is the word you will look for duplicates in
String temp = ""; //In this string, you will add characters that are not duplicates
boolean isDuplicate = false; //This will reset every out iteration

I'm using a hard example to keep things simple. Please understand that the String temp will start empty, but when your whole process is done, your goal is to have temp have the same characters as einstein without duplicates. Something like stein

public static void main (String[] args) {

    String s = "einstein";
    String temp = "";
    boolean isDuplicate = false;

    for (int i = 0; i < s.length(); i++) {
        isDuplicate = false;
        char comparisonChar = s.charAt(i);
        for (int j = i + 1; j < s.length(); j++) {
            char nextChar = s.charAt(j);
            if (comparisonChar == nextChar) isDuplicate = true;
        }
        if (!isDuplicate) temp = temp + comparisonChar;
    }

    System.out.println(temp); //should print `stein`
}

}

Now I haven't tested this so it's likely it has bugs, but walk through it mentally and try to understand it. Ask me when confused.

查看更多
三岁会撩人
7楼-- · 2019-09-04 12:35

Well, I can see what approach you were trying to use. First of all, when you say "removing duplicates", are you only removing duplicates that are next to each other? In other words, you want to change "bookkeeper" to "bokeper" but "abcabcabc" doesn't get changed. If you want to return just "abc" for the second one, your whole approach is wrong.

Assuming you want to remove just the duplicates that are next to each other, you were sort of on the right track, but here's what you did wrong:

(1) When you go through looking at each character in userKeyword, like this:

for (lengthCounter=0; lengthCounter<wordLength; lengthCounter++){
    if (userKeyword.charAt(lengthCounter) != userKeyword.charAt(lengthCounter + 1)){

you will get messed up if you change userKeyword inside the loop, as you did. The characters will shift over, but you'll keep incrementing the index, which means you will skip over some characters.

(2) Since you're looking at the characters at lengthCounter and lengthCounter+1, you have t be careful when you reach the end of the string. In this case, you don't want the index to reach the last character, because there is no character after it, and charAt(lengthCounter + 1) will crash. Change the for to say lengthCounter < wordLength-1.

(3) Finally, you're setting revisedKeyword and userKeyword to a one-character string.

String revisedKeyword = "" + userKeyword.charAt(lengthCounter);
userKeyword = revisedKeyword;

This certainly can't be what you want. You probably want to set up a new String to hold the entire keyword. Something like this: put this outside the loop

String newKeyword = "";

and then, to add a new character to it

newKeyword = newKeyword + userKeyword.charAt(lengthCounter);

and don't change userKeyword inside the loop; then at the end, newKeyword will be the answer.

(I'm assuming you need to learn how to use loops and stuff. In real life, I think I could do the whole thing in one line with a regex, but that's not the point of the exercise.)

查看更多
登录 后发表回答