使用 java 给出错误字符的字符串中的第一个非重复字符?

first non repeated character in a string giving wrong character using java?

我已经编写了代码来打印字符串中的第一个非重复字符一切正常fine.But同时打印它的字符它给出null.Example来自Sting input="ttaasjji kkk eee"然后它应该打印's' 因为第一个不重复 character.Following 是我的 java 代码。

public static void main(String[] args) {
    LinkedHashMap hm = new LinkedHashMap();
    //HashMap hm=new HashMap();
    String input = "ttaasjjikkk eee ";
    input = input.trim();
    for (int i = 0; i < input.length(); i++) {
        char c = input.charAt(i);
        Integer val = (Integer) hm.get(c);
        if (c != ' ') {//to exclude space count
            if (val != null) {
                hm.put(c, val + 1);
            } else {
                hm.put(c, 1);
            }
        }
    }
    System.out.println(hm);//each char count      
    Iterator itr = (Iterator) hm.keySet().iterator();
    while (itr.hasNext()) {
        Object temp = hm.get(itr.next());
        String sTemp = temp.toString();
        int value = Integer.parseInt(sTemp);
        if (value == 1) {
            System.out.println("First non repeated character is: " + hm.get(temp) + "," + temp);
            return;
        }
    }
}

请帮助我,我们将不胜感激。

你打印错了。您应该打印值为 1 的第一个键(字符)。

相反,您正在打印 hm.get(temp),它是空的,因为 temp 是一个 Integer 并且您的地图没有 Integer 键。

应该是:

while (itr.hasNext()) {
    Character key = (Character) itr.next();
    Object temp = hm.get(key);
    String sTemp = temp.toString();
    int value = Integer.parseInt(sTemp);
    if (value == 1) {
        System.out.println("First non repeated character is: " + key + "," + temp);
        return;
    }
}

我建议你使用参数化类型,以避免这种混淆。使用 LinkedHashMap<Character,Integer>.

而不是原始 LinkedHashMap

输出:

{t=2, a=2, s=1, j=2, i=1, k=3, e=3}
First non repeated character is: s,1

您正在使用地图的键集。您需要 entry-set 以便您可以检查每个条目的值。这就是存储计数的内容 - 无需将字符串解析为整数。

您还应该修复所有代码以使用泛型,以避免所有转换:

import java.util.*;

class Test {
   public static void main(String[] args) {
       // Key type is Character, value type is Integer
       Map<Character, Integer> map = new LinkedHashMap<>();
       String input = "ttaasjjikkk eee ";
       input = input.trim();
       for (int i = 0; i < input.length(); i++) {
           char c = input.charAt(i);
           Integer val = map.get(c);
           if (c != ' ') {
               if (val != null) {
                   map.put(c, val + 1);
               } else {
                   map.put(c, 1);
               }
           }
       }

       System.out.println(map);

       // Enhanced for loop to make it easier to iterate
       for (Map.Entry<Character, Integer> entry : map.entrySet()) {
           if (entry.getValue() == 1) {
               System.out.println("First non repeated character is: " 
                   + entry.getKey());
               return;
           }
       }
   }
}