Shivam Sharma :
public class NoDuplicate {
static final int NO_OF_CHARS = 256;
/* Print duplicates present in the passed string */
static void printDistinct(String str)
{
// Create an array of size 256 and count of
// every character in it
int[] count = new int[NO_OF_CHARS];
/* Count array with frequency of characters */
int i;
for (i = 0; i < str.length(); i++)
if(str.charAt(i)!=' ')
count[(int)str.charAt(i)]++;
int n = i;
// Print characters having count more than 0
for (i = 0; i < n; i++)
if (count[(int)str.charAt(i)] == 1)
System.out.print(str.charAt(i));
}
/* Driver program*/
public static void main(String args[])
{
String str = "SHINCHAN";
printDistinct(str);
}
}
I am trying to store the distinct characters in a string. The problem is that my code remove all duplicate elements. Example:
Input:
SHINCHAN
Actual output:
SICA
Desired output:
SHINCA
(I want to store each element once)
Nicholas K :
You can make use of a LinkedHashSet
to implement the same :
static void printDistinct(String str) {
Set<Character> origSet = new LinkedHashSet<Character>();
StringBuilder concat = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (origSet.add(str.charAt(i))) {
concat.append(str.charAt(i));
}
}
System.out.println(concat);
}
If you are using java-8, you can just do :
str.chars().mapToObj(e -> Character.toString((char) e))
.distinct()
.forEach(System.out::println);