为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

呼唤远方 2023-07-19 15:38:55
我正在尝试计算字符串中字母的出现次数。我在技术上编写的代码可以实现我想要的功能,但不是按照我想要的方式实现。例如,如果我输入“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)] + " ");                }            }         }    }
查看完整描述

2 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

你只需要一个 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]);


查看完整回答
反对 回复 2023-07-19
?
月关宝盒

TA贡献1772条经验 获得超5个赞

更改str = scan.nextLine();str = scan.nextLine().toLowerCase().replaceAll("\\s+","");

.toLowerCase()是一种使字符串中的每个字符都小写的方法。

.replaceAll()是一种用另一个字符替换一个字符的方法。在这种情况下,它将空白替换为空。


查看完整回答
反对 回复 2023-07-19
  • 2 回答
  • 0 关注
  • 85 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信