如何解决:字符串中字母出现的次数

我正在尝试计算字符串中字母的出现次数。我在技术上编写的代码可以实现我想要的功能,但不是按照我想要的方式实现。例如,如果我输入“Hello World”,我希望我的代码返回“a=0 b=0 c=0 d=0 e=1 etc....”,而我编写的代码返回“H= 1、e=1、l=2 等等……”


另外我如何确保它不区分大小写并且不计算空格。


代码:


    import java.util.Scanner;


    public class Sequence {

    private static Scanner scan = null;


    public static void main(String[] args) {

        scan = new Scanner(System.in);

        String str = null;

        System.out.print("Type text: ");

        str = scan.nextLine();


        int[] count = new int[255];


        int length = str.length();


            for (int i = 0; i < length; i++) 

            {

                count[str.charAt(i)]++;

            }


            char[] ch = new char[str.length()];


            for (int i = 0; i < length; i++) 

            {

                ch[i] = str.charAt(i);

                int find = 0;


                for (int j = 0; j <= i; j++) 

                {

                    if (str.charAt(i) == ch[j])

                find++;

                }


                if (find == 1) 

                {

                    System.out.print(str.charAt(i) + "=" + count[str.charAt(i)] + " ");

                }

            }


         }

    }


呼唤远方
浏览 87回答 2
2回答

慕村225694

你只需要一个 26 (s) 的数组int,因为字母表中只有 26 个字母。在分享代码之前,请务必注意 Javachar是整型(例如,'a' + 1 == 'b')。该属性很重要,因为它允许您确定数组中的正确偏移量(特别是如果您强制输入为小写)。就像是,Scanner scan = new Scanner(System.in);System.out.print("Type text: ");String str = scan.nextLine();int[] count = new int[26];for (int i = 0; i < str.length(); i++) {    char ch = Character.toLowerCase(str.charAt(i)); // not case sensitive    if (ch >= 'a' && ch <= 'z') { // don't count "spaces" (or anything non-letter)        count[ch - 'a']++; // as 'a' + 1 == 'b', so 'b' - 'a' == 1    }}for (int i = 0; i < count.length; i++) {    if (count[i] != 0) {        System.out.printf("%c=%d ", 'a' + i, count[i]);    }}System.out.println();如果您确实想查看所有计数为零的字母(对我来说似乎毫无意义),请更改if (count[i] != 0) {    System.out.printf("%c=%d ", 'a' + i, count[i]);}删除if并且只是System.out.printf("%c=%d ", 'a' + i, count[i]);

月关宝盒

更改str = scan.nextLine();为str = scan.nextLine().toLowerCase().replaceAll("\\s+","");.toLowerCase()是一种使字符串中的每个字符都小写的方法。.replaceAll()是一种用另一个字符替换一个字符的方法。在这种情况下,它将空白替换为空。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java