0
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.

3
  • Do you have a question? Commented Aug 10, 2013 at 0:13
  • Oh, how do I remove the duplicate characters in a user Inputted String only using loops charAt() and indexOf()......Thanks. Commented Aug 10, 2013 at 0:29
  • Make a new string: String result = ""; for ... if not duplicate { result = result + charAt; } return result; Commented Jun 13, 2018 at 14:05

8 Answers 8

4

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.

Sign up to request clarification or add additional context in comments.

20 Comments

Thanks for your reply.... I would used Sets but we havent been taught that yet...They want us to onl use indexOF and charAt methods... (and maybe loops).... is there any way? If there is no other way then I guess I might have to use Sets. and I need to return the value and not print it out).
There is a way. The idea is, you loop over each character of your String using charAt(index). In this loop, you set up ANOTHER loop, which starts at the NEXT character and goes to the end. In this inner loop, you simply compare the outer loop character with the inner loop character. If there are no matches, you then add this outer loop character to some other String a = "" (starts empty)
AH i see,, yeah, just realized that my code actually just trying to check the char next to it. But if i was to do internal loops into each of the loops would my code return the value.
Yes it will, and you only have to use two loops with one nested inside of the other. Just try to get your mind around the idea before starting to write code. Your string is a bunch of characters. You can get at each character one by one. Once you have a character, you can compare it to all the characters in the remainder of the string. Maybe get out a piece of paper and write out a step by step of how you expect the computer to act. If you need more help let me know.
How do I make a loop comparing the 1st char to the (comparison of the 2nd and the rest) of the characters? Thanks for your help man, been only coding for a week or two.
|
0

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.)

1 Comment

Ah I see. yeah, I figured that's what caused the crashes... what do _I put for return; ? return newKeyword;?
0

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;
}

Comments

0

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.

Comments

0
String removeDuplicates(String s) {

    //Unicode characters range from 0x0000 to 0xFFFF
    boolean[] marker = new boolean[0xFFFF]; 

    StringBuilder sb = new StringBuilder();

    for(int i =0; i< s.length();i++) {
        char c = s.charAt(i);

        if(marker[c] == false) {
            //Character is first time occurred
            sb.append(c);

            //mark character as occurred
            marker[c] = true; 
        }
    }
    return sb.toString();
}

Comments

0

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);

    }

}

2 Comments

Could you explain how this answers the question?
just take the input string from BufferedReader as BufferedReader br=new BufferedReader(new inputStreamReader(System.in)); String st=br.readLine and then proceed with previous explained manner
0
class Twice_Occuring
{
    void main(String s)
    {
        int count=0;
        for(int i=0;i<s.length();i++)
        {
            char c=s.charAt(i);
            int ind1=s.indexOf(c,i);
            int ind2=s.indexOf(c,i+1);
            if(ind2-ind1==1)
            {
                System.out.print(c+" ");
                count++;
            }
        }
        System.out.println("\n Number of counts = "+count);
    }
}

1 Comment

Would you consider expanding on your answer a bit and explaining what is going on in your code? That would make this answer much more useful for future visitors.
0
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);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.