0

我不知道该怎么做。

假设我有多个这样的字符串,也许在一个列表中。

ABSKSNFASLKFSAF

LKGEROGNDFKGDFD

GKDFLGSDFLGDFSJ

我想计算每列中每个字母的出现次数。所以第一列是“ALG”,因此 A 的出现是 1,L 是 1,G 是 1。第十列是“LFL”,L 的出现是 2,F 是 1 等等。

字符串的长度都是一样的。

public static void main(String[] args) throws Exception
{
ArrayList<String> strings = new ArrayList<String>();
strings.add(“ABSKSNFASLKFSAF”);
strings.add(“LKGEROGNDFKGDFD”);
strings.add(“GKDFLGSDFLGDFSJ”);

List<Character> column1 = new ArrayList<Character>();
for(String s : strings)
    column1.add(s[0]);

}

提前致谢。

4

1 回答 1

1
public class ColumnCharacterCount {
    private static final HashMap<Integer, HashMap<Character, Integer>> map =
            new HashMap<Integer, HashMap<Character, Integer>>();
    public static void main(String[] args) {
        ArrayList<String> strings = new ArrayList<String>();
        strings.add("ABSKSNFASLKFSAF");
        strings.add("LKGEROGNDFKGDFD");
        strings.add("GKDFLGSDFLGDFSJ");
        for (String str : strings) {
            for (int col = 0; col < str.length(); col++) {
                Character c = str.charAt(col);
                HashMap<Character, Integer> colMap = map.get(col);
                if (colMap == null) {
                    colMap = new HashMap<Character, Integer>();
                    map.put(col, colMap);
                }
                Integer charCounter = colMap.get(c);
                if (charCounter == null) {
                    charCounter = 0;
                }
                charCounter++;
                colMap.put(c, charCounter);
            }
        }
        Set<Entry<Integer, HashMap<Character, Integer>>> entrySet =
                map.entrySet();
        for (Entry<Integer, HashMap<Character, Integer>> entry : entrySet) {
            Integer key = entry.getKey();
            HashMap<Character, Integer> value = entry.getValue();
            System.out.printf("Column %2d has %s %n", key, value);
        }
    }
}

输出:

Column  0 has {G=1, A=1, L=1} 
Column  1 has {B=1, K=2} 
Column  2 has {D=1, G=1, S=1} 
Column  3 has {E=1, F=1, K=1} 
Column  4 has {S=1, R=1, L=1} 
Column  5 has {G=1, N=1, O=1} 
Column  6 has {F=1, G=1, S=1} 
Column  7 has {D=1, A=1, N=1} 
Column  8 has {D=1, F=1, S=1} 
Column  9 has {F=1, L=2} 
Column 10 has {G=1, K=2} 
Column 11 has {D=1, F=1, G=1} 
Column 12 has {D=1, F=1, S=1} 
Column 13 has {F=1, A=1, S=1} 
Column 14 has {D=1, F=1, J=1} 
于 2013-11-05T23:06:31.080 回答