get substring Count - Java java.lang

Java examples for java.lang:String Substring

Description

get substring Count

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String string = "java2s.com";
        String subString = "com";
        System.out.println(getsubstringCount(string, subString));
    }//from w  w  w . j  ava 2 s .  co  m

    public static int getsubstringCount(String string, String subString) {
        String s = String.copyValueOf(string.toCharArray());
        String ToFind = subString;
        int index = 0;
        int count = 0;
        while (index != -1) {
            index = s.indexOf(ToFind);
            if (index == -1) {
                break;
            }
            s = s.substring(index + ToFind.length());
            count++;

        }
        return count;

    }
}

Related Tutorials