count Occurrences of sub string in a string - Java java.lang

Java examples for java.lang:String Substring

Description

count Occurrences of sub string in a string

Demo Code


//package com.java2s;

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

    public static int countOccurrences(String haystack, char needle) {
        int count = 0;
        for (int i = 0; i < haystack.length(); i++) {
            if (haystack.charAt(i) == needle) {
                count++;
            }
        }
        return count;
    }
}

Related Tutorials