Counting the number of specific occurrences in a java string

I am trying to solve a problem when I create a method that counts the number of capital and lowercase entries ("A" or "a") in a specific string. I have been working on this problem for a week now, and the main error I get is that "char cannot be dereferenced." Can someone point me in the right direction to this Java issue? Thanks.

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 } } 
+5
source share
4 answers

try a simpler solution

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

Just as @chris mentions in his answer, String can be converted to lowercase first and then only perform one check

+4
source

The main error I get is that "char cannot be dereferenced"

change this:

 s.length // this syntax is incorrect 

:

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

also change this:

 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 

another solution to accomplish your task is simpler using the Stream#filter method. Then convert each String in Stream to lowercase before comparison, if any strings match "a" , we save it if we don't ignore it, and in the end we just return the count.

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

To count the amount of time, 'a' or 'a' appears in the line:

 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; } 

Or just replace everything else and see how long your line is:

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

To find the number of characters a and A , appears on the line .

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

Source: https://habr.com/ru/post/1267209/


All Articles