0

To remove a character from a string s in JAVA.Here replace function is not working for me to remove a character.


    class DuplicateLetter{
        public static void main(String[] abs) {
            duplicate("pbbcggttcoos", 2);
        }

        private static void duplicate(String s, int k) {
            int length = s.length();
            char letter [] = s.toCharArray();
            for(int i = 0; i < length; i++) {
                if(i > 1) {
                if(letter[i] == letter[i-1]) {

                    //remove the character
                    s.replace(letter[i], "");
                }
                }
            }

        }
    }

  • `s.replace` returns a new String as result, without modifying the original one. Try `s = s.repace...`. – Johannes Kuhn Nov 03 '19 at 01:39
  • Check [this](https://stackoverflow.com/questions/4989091/removing-duplicates-from-a-string-in-java) out. – Raj Nov 03 '19 at 01:41

1 Answers1

0

Java string is an immutable object, then you can't modify it directly, replace this code :

s.replace(letter[i], "");

By :

s = s.replace(letter[i],Character.MIN_VALUE);
Mohamed IMLI
  • 38
  • 1
  • 8
  • The replace(char, char) function accepts 'char' as argument. At first, you cannot provide a string (double quotes) as a replacement. In addition, it also won't accept an empty literal. – Venkata Rathnam Nov 03 '19 at 01:46
  • 1
    Yes ! But this should works : s = s.replace(letter[i],Character.MIN_VALUE) – Mohamed IMLI Nov 03 '19 at 01:54
  • @MohamedIMLI - In the OP's case, it doesn't. He defines a `duplicate` method that doesn't return a value. Simply updating `s` doesn't make that method work as the OP intends it to work. – Stephen C Nov 03 '19 at 02:14