Pages

Find first unique character in string

Find first unique character in string



  • In java we can find first non-repeated/unique character in string by using LinkedHashMap as it maintains insertion order.
Program:
  • First we will find count of each character in given string and will store each character count/occurence in linkedHashMap. Based on count value we will get first unique character in given string.
import java.util.LinkedHashMap;
import java.util.Map.Entry;

public class FirstUniqueCharacter {
public static void main(String[] args) {

String str = "elephantL";
str = str.toLowerCase();

char[] carr = str.toCharArray();

LinkedHashMap<Character, Integer> lmap = new LinkedHashMap<Character, Integer>();

for (char c : carr) {
if (lmap.containsKey(c)) {
lmap.put(c, lmap.get(c) + 1);
} else {
lmap.put(c, 1);
}
}

for (Entry<Character, Integer> entry : lmap.entrySet()) {
if (entry.getValue() == 1) {
System.out.print(entry.getKey());
break;
}
}

}
}
Output:
Find first unique character in string
Find first unique character in string

Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.