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

How do I count the characters in a string and then sort them alphabetically?

我正在听取用户的意见。我已经完成了那一点。输入可以是一个词,甚至可以是一个保存为字符串的句子。我想做的是计算字母在输入中出现的次数,并按字母顺序排序。

示例输入:

learning to program

示例输出:

a 2
e 1
g 2
i 1

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

 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)));
    }

这里解释了如何计算字符串中的出现次数: 我试图在这段代码中模仿您的示例输出 fiddle.

我使用的方法: Sort Map

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))

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

排序字符串“aabbbcddeeee”的简单解决方案之一然后输出:a2b3c1d2e4

public static void main(String[] args) {
            
    String input = "aabbbcddeeee"; // output: a2b3c1d2e4
    int count = 0;
    int i = 0;
    int k = 0;
    
    for (i = 0; i < input.length(); i++) {
        
        for (int j = i; j < input.length(); j++) {
            
            if (input.charAt(i) == input.charAt(j)) {
                
                count = count + 1;
                k++;
            } else
                break;
        }
        System.out.print(input.charAt(i));
        System.out.print(count+"\n");
        i = k - 1;
        count = 0;     // reset counter
    }
}

这个怎么样;

const test ="the quick brown fox jumps over the lazy dog";
const letterMap = {};
[...test].forEach(x=>{letterMap[x]?letterMap[x]++:(letterMap[x]=1)});
console.log (Object.keys(letterMap).sort().map((key) => [key, letterMap[key]]));

输出;

[[" ",8],["a",1],["b",1],["c",1],["d",1],["e",3],["f",1],["g",1],["h",2],["i",1],["j",1],["k",1],["l",1],["m",1],["n",1],["o",4],["p",1],["q",1],["r",2],["s",1],["t",2],["u",2],["v",1],["w",1],["x",1],["y",1],["z",1]]