gpt4 book ai didi

java - 如何修复: Number of occurrences of a letter in a string

转载 作者:行者123 更新时间:2023-12-02 00:50:36 24 4
gpt4 key购买 nike

我正在尝试计算字符串中字母出现的次数。我在技术上编写的代码可以实现我想要的功能,但不是按照我想要的方式实现。例如,如果我输入“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)] + " ");
}
}

}
}

最佳答案

正如我暗示的那样 in my original comment你只需要一个 26 个 int 的数组,因为字母表中只有 26 个字母。在分享代码之前,请务必注意 Java char 是整型(例如,'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]);

关于java - 如何修复: Number of occurrences of a letter in a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57862463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com