Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Java String Maniplulation

Name: Anonymous 2011-05-22 22:37

this doesn't work if the first letter has a duplicate at the end. what am i doing wrong?

    /**
     * Removes duplicate characters. Only latter instances<br/>
     * are deleted
     * @param s - the original
     * @return the string with dupes removed
     */
    public static String removeDuplicates(String s){
        for (int x = 0; x < s.length(); x++){
            for (int k = x + 1 ; k < s.length(); k++){
                if (s.charAt(x) == s.charAt(k))
                    s = s.substring(0, k) + s.substring(k + 1);
            }
        }
        return s;
    }

Name: Anonymous 2011-05-22 23:30

>>1
It's pretty simple. When the duplicate is at the end, evaluating s.substring(k + 1)[/string] breaks because [code]k + 1 > s.length. You can work around this in various ways, but the lazy way that first came to my mind is changing that line to:

s = s.substring(0, k) + (k == s.length - 1 ? s.substring(k + 1) : "");

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List