java - 我想显示字符串中某个字符的出现。我怎样才能改进我的代码?

标签 java string count find-occurrences

<分区>

我想创建一个程序来显示字符串中某个字符的出现次数,并计算它们的数量。现在代码只计算字符数。

我想进行以下更改:

1) 如何让这个程序只计算一种类型的字符,比如 ac 字符串 I love ice cream.

2) 我如何也打印字符串中的字符,假设有两个 d 我的程序将首先显示 2 d

3) 对于 Scanner input = new Scanner(System.in); 部分,我在 eclipse 中遇到错误,说扫描仪无法解析为类型。

也可以随时对代码中需要改进的任何内容发表评论。基本上只需要一个简单的程序来显示字符串中的所有 C,然后计算字符串的出现次数。然后我想自己弄乱代码,更改它以便我可以学习 Java。

到目前为止,这是我的代码:

public class Count { 
    static final int MAX_CHAR = 256; //is this part even needed?

    public static void countString(String str) 
    { 
        // Create an array of size 256 i.e. ASCII_SIZE 
        int count[] = new int[MAX_CHAR]; 

        int length = str.length(); 

        // Initialize count array index 
        for (int i = 0; i < length; i++) 
            count[str.charAt(i)]++; 

        // Create an array of given String size 
        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 any matches found 
                if (str.charAt(i) == ch[j])  
                    find++;                 
            } 

            if (find == 1)  
                System.out.println("Number of Occurrence of " + 
                 str.charAt(i) + " is:" + count[str.charAt(i)]);             
        } 
    } 
    public static void main(String[] args) { 
        Scanner input = new Scanner(System.in); 
        String str = "geeksforgeeks"; 
        countString(str); 
    } 
} 

最佳答案

试试这个

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String str = input.nextLine();

    // Whatever is the input it take the first character.
    char searchKey = input.nextLine().charAt(0);
    countString(str, searchKey);
}

public static void countString(String str, char searchKey) {
    // The count show both number and size of occurrence of searchKey
    String count = ""; 
    for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i) == searchKey)
            count += str.charAt(i) + "\n";
    }
    System.out.println(count + "\nNumber of Occurrence of "
                    + searchKey + " is " + count.length() + " in string " + str);
}

关于java - 我想显示字符串中某个字符的出现。我怎样才能改进我的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52350940/

相关文章:

java - 是否可以在构造函数内实现接口(interface)?

java - Spring 事务不回滚

java - 声明 String s= new String ("abc").intern(); 有什么好处?在 String s ="abc"上(反之亦然)

mysql - SELECT DISTINCT 并计数

mysql - 使用多个 LEFT JOIN 时,COUNT 和 SUM 会相乘

java - 如何将重音字符传递给 REST API(Github 问题)?

java - 从服务发送数据到远程套接字时出现问题

java - 比较java中的两个字符串并识别重复的单词

JavaScript/正则表达式 : Delete a specific Text (word) starting with a specific letter inside a String with words separated by spaces

java - 计算 Java 类的代码行数