Write a program to print after removing duplicates from a given string


The program starts by defining a main() method that initializes a string variable str with the value "Java Exercises" and then calls the removeDuplicate() method passing str as a parameter.

The removeDuplicate() method accepts a string parameter s, converts it to a character array using the toCharArray() method, and initializes a new string str as an empty string.

Then, it iterates through each character in the character array using a for-each loop. For each character, it checks if it already exists in the str using the indexOf() method. If the character is not present in str, it appends that character to the str using the += operator.

Finally, the method prints the resulting string with unique characters to the console using the System.out.println() method. Overall, this program removes duplicate characters from a given string by iterating through each character, checking if it already exists in a separate string, and appending it if it's not already present.

Source Code

class Remove_Duplicates
{
	public static void main(String[] args)
	{
		String str = "Java Exercises";
		System.out.println("Given String : " + str);
		removeDuplicate(str);
	}
	private static void removeDuplicate(String s)
	{
		char[] arr = s.toCharArray();
		String str = "";
		for (char e: arr)
		{
			if (str.indexOf(e) == -1)
			{
				str += e;
			}
		}
		System.out.println("After Removing duplicates characters in string is: " + str);
	}
}

Output

Given String : Java Exercises
After Removing duplicates characters in string is: Jav Exercis

Example Programs