Below program illustrates how to print first non-repeating character in given String using Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
public class FirstNonRepeatedChar { public static void main(String[] args) throws Exception { String s = "Aishwarya Roy"; System.out.println(findFirstNonRepeatedChar(s)); } private static char findFirstNonRepeatedChar(String s) throws Exception { Map s = s.toLowerCase(); char[] chars = s.toCharArray(); for(char c : chars) { if(map.containsKey(c)) { map.put(c, map.get(c) + 1); } else { map.put(c, 1); } } for(Character chr : map.keySet()) { if(map.get(chr) == 1) { return chr; } } throw new Exception("Didn't find any repeating character."); } } |