我如何计算字符串中的字符,然后按字母顺序对它们进行排序?

问题描述 投票:-1回答:2

我正在接受用户的输入。我已经完成了。输入可以是单词,也可以是保存为字符串的句子。然后,我要计算的是字母在输入中出现的次数,并按字母顺序对其进行排序。

示例输入:

learning to program

示例输出:

a 2
e 1
g 2
i 1
java sorting count alphabetical
2个回答
0
投票

我为您编写了一些代码,应该可以解决问题:)

 String name = "doodleice";

    HashMap<Character, Integer> charMap = new HashMap<>();

    char[] charArray = name.toCharArray();

    for(int i = 0; i < charArray.length; i++){
        if(charMap.containsKey(charArray[i])){
            charMap.put(charArray[i], charMap.get(charArray[i]) + 1);
        }
        else{
            charMap.put(charArray[i], 1);
        }
    }

    ArrayList<Character> charList = new ArrayList<>();
    for(Map.Entry<Character, Integer> entry: charMap.entrySet()){
        charList.add(entry.getKey());
    }

    Collections.sort(charList);

    for(int i = 0; i < charList.size(); i++){
        System.out.println(charList.get(i) + " " + charMap.get(charList.get(i)));
    }

0
投票

这里说明了如何计算字符串中的出现次数:https://stackoverflow.com/a/881111/8935250我试图在此代码小提琴中模仿您的示例输出。

我使用的方法:SortMap

const string = "learning to program"

function count(character) {
	return string.split(character).length
}

map = string.split("").map(c => {
	return {c, count: count(c)}
})

map.sort((a,b) => b.count - a.count)

console.log(map)
console.log(string.split("").sort((a,b) => string.split(b).length - string.split(a).length))

也应该做这项工作,但不显示出现的情况。

© www.soinside.com 2019 - 2024. All rights reserved.