title: Counting number of occurrences of word in java
body: <p>I want to count the number of occurrences of particular word in a source string.
  Let's say src="thisisamangoterrthisismangorightthis?"
       word="this"
  So what I am doing is, first search for index of word in src. It's at index 0. Now I am extracting the part from this index location to end of src.
  i.e., now src="isamangoterrthisismangorightthis?" and search for word again.
  But I am getting array out of bound exception.</p>
  
  <pre><code>public static int countOccur(String s1, String s2)
  {
      int ans=0;
      int len1=s1.length();
      int len2=s2.length();
      System.out.println("Lengths:"+len1+" " +len2);
  
      while(s1.contains(s2))
      {
          ans++;
          int tmpInd=s1.indexOf(s2);
          System.out.println("Now Index is:"+tmpInd);
          if((tmpInd+len2)&lt;len1){
              s1=s1.substring(tmpInd+len2, len1);
              System.out.println("Now s1 is:"+s1);
          }
          else
              break;
      }
      return ans;
  
  }
  </code></pre>