0

I'm trying to write a code that takes in a String and removes repeating characters in that String.

String utenRepetisjon(String tekst) {

    String b;

    char[] tekstArray = tekst.toCharArray();
    char[] tilTekst = new char[tekstArray.length];

    for(int i=0; i<tekstArray.length; i++) {
        for(int j=0; j<tekst.length(); j++) {
            if(tekstArray[i] != tekst.charAt(j)) {
                tilTekst[i] = tekstArray[i];
            }
        }
    }
    return b = new String(tilTekst);
}

E.g. If tekst = "aababbabbac", it should return "abc". So far my code only return the same tekst that it's given..

Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
patski
  • 329
  • 6
  • 15
  • 1
    Take a look at this link: http://stackoverflow.com/questions/4989091/removing-duplicates-from-a-string-in-java – T0to Nov 28 '13 at 15:38
  • How is your code supposed to work? tilTekst is created with the same length as tekst, which makes no sense in your problem because returned string is quite often smaller. – Pierre Arlaud Nov 28 '13 at 15:40

2 Answers2

5

Try the next:

String utenRepetisjon(String tekst) {
    String str = "";
    for(char ch : tekst.toCharArray()) {
        if (str.indexOf(ch) == -1) {
            str += ch;
        }
    }
    return str;
}
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
-1

Here's the code. Use a hashmap

 String tekst = "aababbabbac";
    char[] testArray = tekst.toCharArray();
    Hashtable<String, String> hash = new Hashtable<String, String>();
    for (char c : testArray) {
        if (!hash.containsKey("" + c)) {
            hash.put("" + c, "1");
        }
    }
    String dups = "";
    for (String key : hash.keySet()) {
        dups+=key;
    }
    System.out.println(dups);
sanket
  • 789
  • 4
  • 16