Remove duplicate characters from the string


 

Remove duplicate characters from the string

In this tutorial, you will learn how to remove duplicate characters from the string.

In this tutorial, you will learn how to remove duplicate characters from the string.

Remove duplicate characters from the string

In this tutorial, you will learn how to remove duplicate characters from the string.

Java has provide several methods to examine the content of string, finding characters or substrings within a string, changing case etc. You can manipulate the string in various ways. Here we are going to remove duplicate characters from the string. For this, we have created a method removeDuplicates() that accepts the string and iterate through the for loop to find the duplicates from the string and append unique characters to StringBuilder. The method returns the string free from duplicate characters.

Example:

import java.util.*;
class RemoveDuplicateCharatcersFromString 
{
public static String removeDuplicates(String s) {
StringBuilder build = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
String st = s.substring(i, i + 1);
if (build.indexOf(st) == -1) {
build.append(st);
}
}
return build.toString();
}
public static void main(String[] args) 
{
String str="Hello World";
String newString=removeDuplicates(str);
System.out.println(newString); 
}
}

Output:

String is: Hello World
After removing the character r, string is: Hello Wold

Ads