簡體   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