How to find the frequency of characters in a string in Haskell?

前端 未结 7 1289
谎友^
谎友^ 2020-12-11 15:08

How can I count the frequency of characters in a string and then output them in sort of a table?

For example, if I input the word \"happy\" the result would be

7条回答
  •  悲哀的现实
    2020-12-11 15:20

    //Count the frequency of character in a string 
    
    package waytocreateobject;
    import java.util.Scanner;
    public class Freqchara {
    
        public static void main(String[] args) {
    
            int c = 0, x = 0, loop = 26, space = 0;
            int count[] = new int[loop];
            //Arrays.fill(count, x);
            Scanner sc = new Scanner(System.in);
            String str =sc.nextLine();
            char[] charr = str.toCharArray();
            int aa = str.length();
            //System.out.println(str.charAt(10));
            //System.out.println(str.charAt(11));
            for (int mm = 0; mm < aa; mm++) {
                if (str.charAt(c) != '\0') {    //Considering characters from 'a' to 'z' only and ignoring others.
                    if ((str.charAt(c) >= 'a') && (str.charAt(c) <= 'z')) {
                        x = (int) str.charAt(c) - (int) 'a';
                        // System.out.println(x);
                        count[x] = count[x] + 1;
                    }
                    c++;
                } else {}
            }
    
            // printing all the charcter
            int i = 97;
            for (int j = 0; j < loop; j++) {
                char ch = (char) (i + j);
                System.out.println(ch + "  occurs  " + count[j] + " times in the string");
            }
            System.out.println("  occurs " + space);
        }
    }
    

提交回复
热议问题