繁体   English   中英

计算java String中特定事件的数量

[英]Counting the number of specific occurrences in a java String

我试图解决一个问题,我创建一个方法来计算某个字符串中大写和小写(“A”或“a”)的出现次数。 我已经在这个问题上工作了一个星期了,而我收到的主要错误是“char无法解除引用”。 任何人都可以指出我在这个Java问题上的正确方向吗? 谢谢。

class Main{ 
    public static int countA (String s)
    {
        String s1 = "a";
        String s2 = "A";
        int count = 0;
        for (int i = 0; i < s.length; i++){
            String s3 = s.charAt(i); 
            if (s3.equals(s1) || s3.equals(s2)){
                count += 1;
            }
            else{
                System.out.print("");
            }
        }
    }

   //test case below (dont change):
    public static void main(String[] args){
        System.out.println(countA("aaA")); //3
        System.out.println(countA("aaBBdf8k3AAadnklA")); //6
    }
}

尝试更简单的解决方案

String in = "aaBBdf8k3AAadnklA";
String out = in.replace ("A", "").replace ("a", "");
int lenDiff = in.length () - out.length ();

同样@chris在他的回答中提到,String可以先转换为小写,然后只进行一次检查

我收到的主要错误是“char无法解除引用”

改变这个:

s.length  // this syntax is incorrect

对此:

s.length()  // this is how you invoke the length method on a string

另外,改变这个:

String s3 = s.charAt(i);   // you cannot assign a char type to string type

对此:

String s3 = Character.toString(s.charAt(i));  // convert the char to string

另一种以更简单的方式完成任务的解决方案是使用Stream#filter方法。 然后在比较之前将Stream每个String转换为小写,如果有任何Strings匹配"a"我们保留它,如果不是我们忽略它,最后,我们只返回计数。

public static int countA(String input)
{
    return (int)Arrays.stream(input.split("")).filter(s -> s.toLowerCase().equals("a")).count();
}

用于计算字符串中出现的'a''A'的时间:

public int numberOfA(String s) {
    s = s.toLowerCase();
    int sum = 0;
    for(int i = 0; i < s.length(); i++){
        if(s.charAt(i) == 'a')
            sum++;
    }
    return sum;
}

或者只是替换其他所有内容,看看你的字符串有多长:

int numberOfA = string.replaceAll("[^aA]", "").length();

查找字符aA出现在字符串中的次数

int numA = string.replaceAll("[^aA]","").length();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM