Count Occurence of Needle String in Haystack String, most optimally?

Posted by Taranfx on Stack Overflow See other posts from Stack Overflow or by Taranfx
Published on 2010-03-25T13:26:11Z Indexed on 2010/03/25 13:33 UTC
Read the original article Hit count: 216

Filed under:
|

The Problem is simple Find "ABC" in "ABCDSGDABCSAGAABCCCCAAABAABC"

Here is the solution I propose, I'm looking for any solutions that might be better than this one.

public static void main(String[] args) {
 String haystack = "ABCDSGDABCSAGAABCCCCAAABAABC";
 String needle = "ABC";
 char [] needl = needle.toCharArray();
 int needleLen = needle.length();
 int found=0;
 char hay[] = haystack.toCharArray();
 int index =0;
 int chMatched =0;

 for (int i=0; i<hay.length; i++){

  if (index >= needleLen || chMatched==0)
   index=0;
  System.out.print("\nchar-->"+hay[i] + ", with->"+needl[index]);

  if(hay[i] == needl[index]){
   chMatched++;
   System.out.println(", matched");
  }else {
   chMatched=0;
   index=0;
   if(hay[i] == needl[index]){
    chMatched++;
    System.out.print("\nchar->"+hay[i] + ", with->"+needl[index]);
    System.out.print(", matched");
   }else
   continue;
  }

  if(chMatched == needleLen){
   found++;
   System.out.println("found. Total ->"+found);
  }
  index++;
 } 
 System.out.println("Result Found-->"+found);
 }

It took me a while creating this one. Can someone suggest a better solution (if any) P.S. Drop the sysouts if they look messy to you.

© Stack Overflow or respective owner

Related posts about java

Related posts about algorithm