Java 程序查找字符串中字符的出现次数


2022年2月6日, Learn eTutorial
1467

在这里,我们将解释如何编写一个 Java 程序来查找字符串中字符的出现次数。所以首先我们必须从用户那里读取字符串,然后我们将调用 `countChar()` 函数来查找字符的出现次数。

如何在 Java 中读取字符串?

为了在 Java 中从用户读取字符串,我们可以使用 Java Scanner 类中的 nextLine() 函数。在这个程序中,我们必须将用户想要检查的字符串读取到字符串变量 **str** 中。所以我们必须像下面这样编写代码:

System.out.println("Enter a string : ");
System.out.println("Enter a string : ");
 

如何实现 Java 程序来查找字符串中字符的出现次数?

首先,我们必须声明类 CCount。然后打开 main 函数。然后从用户那里将字符串读取到变量 str 中,并调用函数 countChar(str) 来查找字符串中每个字符的出现次数。

在 `countChar(str)` 函数中,首先声明一个大小为 **256** 的数组 **c[]**。数组 **c[]** 用于保存每个字符的计数器值。然后使用函数 `str.length()` 将字符串的长度读取到变量 **len** 中。通过使用条件 i 的 for 循环:

算法

步骤 1: 声明具有公共修饰符的类 CCount。

步骤 2:打开 main() 以启动程序,Java 程序执行从 main() 开始

步骤 3: 从用户那里将字符串读取到变量 str 中。

步骤 4: 调用函数 `countChar(str)`。

函数 static void countChar(String str)

步骤 1: 声明数组 **c[]** 为大小为 **256** 的整数。

步骤 2: 将字符串 str 的长度读取到变量 **len** 中。

步骤 3: 使用条件 i 的 `for 循环`:

步骤 4: 创建数组 **array[]**。

步骤 5: 使用另一个条件 i 的 for 循环:

步骤 6: 将 **array[i]** 设置为 **str.charAt(i)**。

步骤 7: 将 flag 设置为零。

步骤 8: 使用另一个条件 **j<=i** 的 for 循环,检查 **str.charAt(i)=array[j]**,如果为 true 则递增 flag。

步骤 9: 将 **i** 递增一并重复步骤 8。

步骤 10: 如果 flag =1,则显示字符的出现次数。

步骤 11: 重复步骤 6。

Java 源代码

                                          import java.util.Scanner;
public class CCount {

    static void countChar(String str) {

        int c[] = new int[256];
        int len = str.length(); //length of the string
        for (int i = 0; i < len; i++)
            c[str.charAt(i)]++;
        char array[] = new char[str.length()]; //Create an array.
        for (int i = 0; i < len; i++) {
            array[i] = str.charAt(i);
            int flag = 0;
            for (int j = 0; j <= i; j++) {
                if (str.charAt(i) == array[j])
                    flag++;
            }

            if (flag == 1)
                System.out.println("Occurrence of char " + str.charAt(i) +
                    " in the String is:" + c[str.charAt(i)]);
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string : ");
        String str = sc.nextLine();
        sc.close();
        countChar(str);
    }
}
                                      

输出

OUTPUT 1
Enter a string : Butterfly
Occurrence of char B in the String is:1
Occurrence of char u in the String is:1
Occurrence of char t in the String is:2
Occurrence of char e in the String is:1
Occurrence of char r in the String is:1
Occurrence of char f in the String is:1
Occurrence of char l in the String is:1
Occurrence of char y in the String is:1