title: Removing a substring from a string, repeatedly
body: <p><strong>Problem:</strong>
  Remove the substring <code>t</code> from a string <code>s</code>, repeatedly and print the number of steps involved to do the same.</p>
  
  <p><strong>Explanation/Working:</strong></p>
  
  <blockquote>
    <p><strong>For Example:</strong>  <code>t = ab</code>, <code>s = aabb</code>. In the first step, we check if <code>t</code> is
    contained within <code>s</code>. Here, <code>t</code> is contained in the middle i.e. <code>a(ab)b</code>.
    So, we will remove it and the resultant will be <code>ab</code> and increment the
    <code>count</code> value by 1. We again check if <code>t</code> is contained within <code>s</code>. Now, <code>t</code> is
    equal to <code>s</code> i.e. <code>(ab)</code>. So, we remove that from <code>s</code> and increment the
    <code>count</code>. So, since <code>t</code> is no more contained in <code>s</code>, we stop and print the
    <code>count</code> value, which is 2 in this case.</p>
  </blockquote>
  
  <p><strong>So, here's what I have tried:</strong></p>
  
  <ol>
  <li><p><strong><em>Code 1:</em></strong></p>
  
  <pre><code>static int maxMoves(String s, String t) {
      int count = 0,i;
  
      while(true)
      {
          if(s.contains(t))
          {
              i = s.indexOf(t);
              s = s.substring(0,i) + s.substring(i + t.length());
          }
          else break;
  
          ++count;
      }
  
      return count;
  }
  </code></pre>
  
  <p>I am just able to pass 9/14 test cases on Hackerrank, due to some reason (I am getting <em>"Wrong Answer"</em> for rest of the cases). After a while, I found out that there is something called <code>replace()</code> method in Java. So, I tried using that by replacing the <code>if</code> condition and came up with a second version of code.</p></li>
  <li><p><strong><em>Code 2:</em></strong></p>
  
  <pre><code>static int maxMoves(String s, String t) {
      int count = 0,i;
  
      while(true)
      {
          if(s.contains(t))
              s.replace(t,""); //Marked Statement
          else break;
  
          ++count;
      }
  
      return count;
  }
  </code></pre>
  
  <p>But for some reason (I don't know why), the <em>"Marked Statement"</em> in the above code gets executed infinitely (this I noticed when I replaced the <em>"Marked Statement"</em> with <code>System.out.println(s.replace(t,""));</code>). I don't the reason for the same.</p></li>
  </ol>
  
  <p>Since, I am passing only 9/14 test cases, there must be some logical error that is leading to a <em>"Wrong Answer"</em>. How do I overcome that if I use <strong>Code 1</strong>? And if I use <strong>Code 2</strong>, how do I avoid infinite execution of the <em>"Marked Statement"</em>? Or is there anyone who would like to suggest me a <strong>Code 3</strong>?</p>
  
  <p>Thank you in advance :)</p>