String Java Programs

Java Program to Remove Duplicates From String

In this tutorial, We will learn writing the java program to remove the duplicate characters from the String. Take any string as an input from the user and check for duplicate characters and if there is any duplicity of characters then remove it.

For example

Case1: If the user inputs the string ‘programmingLanguage’
Then the output should be ‘ogumapenirL’, where there is no character that is repeating.

Case2: If the user inputs the string ‘LearningIsFun’
Then the output should be ‘LergisIauFn’, where there is no character that is repeating.

Java Program to Remove Duplicates From String

import java.util.*;

public class Main {
	public static void main(String[] args) {
		System.out.println("Java program to remove duplicate character");
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter a String");
		String str = sc.nextLine();
		char[] ch = str.toCharArray();
		int len = str.length();
		for (int i = 0; i < len; i++) {
			for (int j = i + 1; j < len; j++) {
				if (ch[i] == ch[j]) {
					for (int k = j; k < len - 1; k++) {
						ch[k] = ch[k + 1];
					}
					len--;
					j--;
				}
			}
		}
		System.out.println("After removing duplicate character");
		for (int i = 0; i < len; i++) {
			System.out.print(ch[i]);
		}
	}
}

Output

Java program to remove duplicate character
Please enter a String
Hitechpoints Website
After removing duplicate character
Hitechpons Wb

Explanation

Here, the user gives input as ‘Hitechpoints Website’, so first, the character of the string gets converted into elements of the set, so the duplicates will get removed.

After that, the elements of the array returned as the output ‘Hitechpons Wb’.

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs