count Char in a String - Java java.lang

Java examples for java.lang:char

Description

count Char in a String

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String src = "java2s.com";
        char c = 'a';
        System.out.println(countChar(src, c));
    }//  www .  ja v a  2s .com

    public static int countChar(String src, char c) {
        int count = 0;
        for (int i = 0; i < src.length(); i++) {
            char spec = src.charAt(i);
            if (spec == c) {
                count++;
            }
        }
        return count;
    }
}

Related Tutorials