Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,914 questions

51,847 answers

573 users

How to remove duplicate letters from string in Java

3 Answers

0 votes
import java.util.HashSet;
import java.util.Set;

public class MyClass {
    public static String removeDuplicateLetters(String str) {
        Set<Character> char_set = new HashSet<>();
        
        for (char ch: str.toCharArray()) {
            char_set.add(ch);
        }
        
        StringBuilder sb = new StringBuilder();
        for (Character ch: char_set) {
            sb.append(ch);
        }

        return sb.toString();
    }
    public static void main(String args[]) {
        String str = "java csharp c c++";
        
        str = removeDuplicateLetters(str);
        
        System.out.println(str);
    }
}




/*
run:

 parcsvhj+

*/

 



answered Jul 17, 2022 by avibootz
0 votes
import java.util.Arrays;

public class MyClass {
    public static String removeDuplicateLetters(char charArr[]) {
        int index = 0, len = charArr.length;
 
        for (int i = 0; i < len; i++) {
            int j;
            for (j = 0; j < i; j++) {
                if (charArr[i] == charArr[j]) {
                    break;
                }
            }
            if (j == i) {
                charArr[index++] = charArr[i];
            }
        }
        return String.valueOf(Arrays.copyOf(charArr, index));
    }
    public static void main(String args[]) {
        String str = "java csharp c c++ php python";
         
        char charArr[] = str.toCharArray();
         
        str = removeDuplicateLetters(charArr);
         
        System.out.println(str);
    }
}
 
 
 
 
/*
run:
 
jav cshrp+yton
 
*/

 



answered Jul 17, 2022 by avibootz
0 votes
public class MyClass {
    public static String removeDuplicateLetters(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 = "java csharp c c++";
         
        str = removeDuplicateLetters(str);
         
        System.out.println(str);
    }
}
 
 
 
 
/*
run:
 
jav cshrp+
 
*/


 



answered Jan 26, 2024 by avibootz

Related questions

1 answer 108 views
1 answer 169 views
3 answers 179 views
3 answers 154 views
3 answers 138 views
1 answer 103 views
3 answers 227 views
...