First non repeating character from string in java

Find first non repeated character from a string using hashmap in java.







import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class NonRepeatingChar{

public static void main(String[] args) {

Scanner scn =new Scanner(System.in);
System.out.println("Type string ");
String s = scn.nextLine();

int index = nonRepeatedChar(s); // non repeating first character

System.out.println(s.charAt(index));
}

public static int nonRepeatedChar(String s) {

Map<Character, Integer> map = new HashMap();
int index =0;

char[] str=s.toCharArray();
for (int i = 0; i < str.length; i++) {

if (map.containsKey(str[i])) {
map.put(str[i], (Integer) map.get(str[i]) + 1);
} else {
map.put(str[i], 1);
}
}
System.out.println(map);
for(int i=0;i<s.length();i++) {
if(map.get(s.charAt(i))==1) {
index = i;
break;
}
}
return index;
}

}





Post a Comment

Previous Post Next Post