how to find unique characters in a string in java
// I would use linkedHashMap since it doesn't accept
// duplicate values
String str = "abbcdddefffggghjilll";
String [] arr = str.split("");
Map<String, Integer> mapStr = new LinkedHashMap<>();
for (int i=0 ; i < arr.length ; i++){
if (!mapStr.containsKey(arr[i])){
mapStr.put(arr[i],1);
} else{
mapStr.put(arr[i],mapStr.get(arr[i])+1);
}
}
for (Map.Entry<String,Integer> map : mapStr.entrySet()) {
if(map.getValue()==1) {
System.out.print(map.getKey());
}
}
3.86
7
public class String_FindtheUnique_4 {
/* Write a return method that can find the unique characters from the String
Ex: unique("AAABBBCCCDEF") ==> "DEF"; */
public static void main(String[] args) {
String result1 = Unique("BBCCDDSSEEDDYUT");
System.out.println(result1); // YUT
//1.yol
String s = "BABABACDR";
String r = "";
for(String each : s.split(""))
r += ( (Collections.frequency(Arrays.asList(s.split("")), each)) ==1 ) ? each : "";
System.out.println(r); // CDR
}
//2.yol method yolu
public static String Unique(String str) {
String result1 ="";
for(String each : str.split(""))
result1 += ( (Collections.frequency(Arrays.asList(str.split("")), each)) ==1 ) ? each : "";
return result1;
}
}
Thank you!
7
0
4
8
// I would use linkedHashMap since it doesn't accept
// duplicate values
String str = "abbcdddefffggghjilll";
String [] arr = str.split("");
Map<String, Integer> mapStr = new LinkedHashMap<>();
for (int i=0 ; i < arr.length ; i++){
if (!mapStr.containsKey(arr[i])){
mapStr.put(arr[i],1);
} else{
mapStr.put(arr[i],mapStr.get(arr[i])+1);
}
}
for (Map.Entry<String,Integer> map : mapStr.entrySet()) {
if(map.getValue()==1) {
System.out.print(map.getKey());
}
}
Thank you!
8
0
Are there any code examples left?
New code examples in category Java