How to remove repeated characters from string in Java

2 Answers

0 votes
public class MyClass {
    public static String removeRepeatedCharactersFromString(String str) {
        StringBuilder sb = new StringBuilder();
        
        str.chars().distinct().forEach(ch -> sb.append((char) ch));
        
        return sb.toString();
    }

    public static void main(String args[]) {
        
        String str = "The quick brown fox jumps over the lazy dog";
        
        str = removeRepeatedCharactersFromString(str);
        
        str = removeRepeatedCharactersFromString(str);
        
        System.out.println(str);
    }
}




/*
run:

The quickbrownfxjmpsvtlazydg

*/

 



answered Sep 13, 2023 by avibootz
0 votes
public class MyClass {
    public static String removeRepeatedCharactersFromString(String str) {
        StringBuilder sb = new StringBuilder();
        
        int index;
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            index = str.indexOf(ch, i + 1);
            if (index == -1) {
                sb.append(ch);
            }
        }
         
        return sb.toString();
    }
 
    public static void main(String args[]) {
         
        String str = "The quick brown fox jumps over the lazy dog";
         
        str = removeRepeatedCharactersFromString(str);
         
        str = removeRepeatedCharactersFromString(str);
         
        System.out.println(str);
    }
}
 
 
 
 
/*
run:
 
Tqickbwnfxjumpsvrthelazy dog
 
*/

 



answered Sep 14, 2023 by avibootz

Related questions

1 answer 158 views
1 answer 129 views
2 answers 222 views
1 answer 94 views
1 answer 148 views
1 answer 113 views
...