To remove duplicate characters from a string in Java, you can use a combination of the charAt
method and the StringBuilder.append
method. Here's an example of how you could do this:
public static String removeDuplicates(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (sb.indexOf(String.valueOf(c)) == -1) { sb.append(c); } } return sb.toString(); }
This function iterates over each character in the input string, s
, and checks whether it has already been added to the StringBuilder
object sb
. If it has not been added, it is appended to sb
. At the end, the StringBuilder
object is converted to a String
and returned.
Here's an example of how you could use this function:
String s = "hello world"; String s2 = removeDuplicates(s); // s2 is "helo wrd"
Note that this function only works for removing duplicates of individual characters. If you want to remove duplicates of substrings, you will need to use a different approach.