How to count occurrences of a character in a String using charAt() in Java

1 Answer

0 votes
package javaapplication1;

import java.io.IOException;

public class JavaApplication1 {

    public static void main(String[] args) throws IOException {

        try {

            String s = "Java Code";
            char ch = 'a';
            int count = 0;
            
            for (int i = 0; i < s.length(); i++) 
                if (s.charAt(i) == ch) 
                    count++;
            
            if (count > 0)
                System.out.println(count + " characters found");
            else
                System.out.println("not found");

        } catch (Exception e) {
            System.out.print(e.toString());
        }
    }
}

/*
           
run:
     
2 characters found
  
 */

 



answered Nov 21, 2016 by avibootz

Related questions

1 answer 154 views
1 answer 239 views
1 answer 157 views
1 answer 202 views
5 answers 358 views
...