Returns the number of occurrences of needle in haystack. - Java java.lang

Java examples for java.lang:String Search

Description

Returns the number of occurrences of needle in haystack.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String haystack = "java2s.com";
        char needle = 'a';
        System.out.println(countOccurrences(haystack, needle));
    }/*from  w  w  w. ja va  2  s. c o  m*/

    /**
     * Returns the number of occurrences of needle in haystack.
     * 
     * @param haystack string to search through
     * @param needle character to find
     * @return number of occurences of needle in haystack
     * 
     * @version 0.2
     * @since 0.2
     */
    public static int countOccurrences(String haystack, char needle) {
        int iCount = 0;
        for (char c : haystack.toCharArray()) {
            if (c == needle) {
                iCount++;
            }
        }
        return iCount;
    }
}

Related Tutorials