Array中给定char的Java出现次数

时间:2014-01-18 12:28:46

标签: java

这是我的作业,我试图在数组的字符串中出现'e'。 我的方法似乎不起作用。任何有智慧的人都可以建议我哪里出错了吗?

import java.util.*;
import java.lang.*;
import java.io.*;

public class CountChar {
    public static void main(String[] args) {
        String[] strings
                = {"hidden", "Java SDK", "DDD", "parameter", "polymorphism", "dictated", "dodged", "cats and dogs"};
        int result = numberOfCharacters(strings, 'e');
        System.out.println("No. of occurrences of 'e' is " + result);
    }

    public static String numberOfCharacters(String str, char a) {
        int aresult = 0;
        if (str.length() > 0) {
            aresult = count(str.substring(1), a) + (str.charAt(0) == a ? 1 : 0);
        }
        return aresult;
    }    
}

3 个答案:

答案 0 :(得分:1)

只需将您的方法签名更改为:

public static String numberOfCharacters(String[] str, char a) {

///code
}

答案 1 :(得分:0)

+1 santosh的回答。我已经按照以下方式尝试过了。试一试

public class CountChar {
public static void main(String[] args) {
    String[] strings
            = {"hidden", "Java SDK", "DDD", "parameter", "polymorphism", 
               "eeeee", "dodged", "cats and dogs"};
    int result = 0;
    for(int i=0;i<strings.length;i++) {
        result += numberOfCharacters(strings[i], 'e');
    }
    System.out.println("No. of occurrences of 'e' in String is "+ result);
}
public static int numberOfCharacters(String str, char a) {
    int counter = 0;
    for( int i=0; i<str.length(); i++ ) {
        if( str.charAt(i)== a ) {
            counter++;
        } 
    }
    return counter;
}    

}

答案 2 :(得分:0)

在一个班轮中:

Arrays.toString(strArray).replaceAll("[^"+a+"]", "").length();

其中'a'是char,'strArray'是字符串数组。

使用关于如何根据这个问题对字符串中的字符进行计数的想法:

Java: How do I count the number of occurrences of a char in a String?

完整代码:

import java.util.Arrays;
public class CountChar {
    public static void main(String[] args) {
        String[] strings
                = {"hidden", "Java SDK", "DDD", "parameter", "polymorphism",
                  "eeeee", "dodged", "cats and dogs"};
        System.out.println("No. of occurrences of 'e' is " + 
                            countCharsInArray(strings, 'e'));
    }

    public static int countCharsInArray(String strArray[], char a) {
        return Arrays.toString(strArray).replaceAll("[^"+a+"]", "").length();
    }
}

解释:

'Arrays.toString(strArray)'将数组转换为单个字符串。  'replaceAll("[^"+a+"]", "")'将空字符'',

替换为我们想要的所有字符

之后我们只需要检查结果字符串的长度。

注意:数组不应该有空值,或者应该先删除它们。