Monday, 29 June 2015

How to find all occurrences of string in a string Java

 Find all occurrences of string in a string. for this we will use one loop and indexof() method

public class StringCheck {
   
    public static void main(String[] args) {
       
        String str = "delhi is good city in india and india also good. there are many city good and people also good" +
                "so india is good country ";
        String mystr = "good";
        int index =0;
   while(index != -1){
       index = str.indexOf(mystr, index+1);
        System.out.println("index is = "+index);
   };
       
    }
}

Output:

index is = 9

index is = 43

index is = 69

index is = 90

index is = 106

index is = -1

No comments:

Post a Comment