Startertutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
Home » Programming » Java » Programs » Strings » Java program to remove duplicate characters from a string
Suryateja Pericherla Categories: Strings. 2 Comments on Java program to remove duplicate characters from a string
0
(0)

In this article we will learn to implement a Java program to remove duplicate characters from a string. A java program is provided below that accepts a string from the user, ignores any duplicate characters and prints each character only once in ascending order.

 

We use TreeSet class from collections framework for printing the characters in ascending order.

 

The program is as follows:

import java.util.*;
public class Sample 
{

	public static void main(String[] args) 
	{
		TreeSet<Character> list = new TreeSet<Character>();
		Scanner input = new Scanner(System.in);
		String s = input.next();
		for(char ch : s.toCharArray())
			list.add(ch);
		for(char ch : list)
			System.out.println(ch);
	}
}

 

Input and output for the above program is as follows:

Input:
asaabebys

Output:
a
b
e
s
y

 


Subscribe to our monthly newsletter. Get notified about latest articles, offers and contests.


If you want to display in insertion order, you can use LinkedHashSet.

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

2 Comments

You can follow any responses to this entry through the RSS 2.0 feed.

Heya i am for the first time here. I came across this board and I
find It really useful & it helped me out a lot.
I hope to give something back and aid others like you aided me.

Hurrah, that’s what I was looking for, what a stuff!
existing here at this weblog, thanks admin of this site.

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory