繁体   English   中英

如何计算字符串中的字符数,然后按字母顺序排序?

[英]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)));
    }

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

我使用的方法: 排序地图

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM