Write a java program to enter a string and display the string by removing duplicate characters .
Answers
Answer:
Java program to remove duplicate characters from a string
Many times we need to remove the duplicate characters from a string in Java. We can remove the duplicate characters from a string by using the simple for loop, sorting, hashing, and IndexOf() method. So, there can be more than one way for removing duplicates.
1) By using the simple for loop.
2) By using the sorting algorithm.
3) By using the hashing.
4) By using the indexOf() method.
Answer:
import java.util.*;
//Creating RemoveDuplicatesExample1 class
class RemoveDuplicatesExample1
{
//Creating removeDuplicates() method to remove duplicates from array
static void removeDuplicate(char str[], int length)
{
//Creating index variable to use it as index in the modified string
int index = 0;
// Traversing character array
for (int i = 0; i < length; i++)
{
// Check whether str[i] is present before or not
int j;
for (j = 0; j < i; j++)
{
if (str[i] == str[j])
{
break;
}
}
// If the character is not present before, add it to resulting string
if (j == i)
{
str[index++] = str[i];
}
}
System.out.println(String.valueOf(Arrays.copyOf(str, index)));
}
// main() method starts
public static void main(String[] args)
{
String info = "javaTpoint is the best learning website";
//Converting string to character array
char str[] = info.toCharArray();
//Calculating length of the character array
int len = str.length;
//Calling removeDuplicates() method to remove duplicate characters
removeDuplicate(str, len);
}
}