title: How do I replace nth character in a String with a new character?
body: <p>I have been asked to write a class that encodes a given sentence using specific rules. This class should use loops and <code>Stringbuffer</code>. The rules are:</p>
  
  <ul>
  <li>Each dot '.' is to be replaced by '*'.</li>
  <li>Every 3rd character (if this character is not a space or a dot)
  should be eliminated.</li>
  <li>Add at the end of the new sentence a number representing total number
  of eliminated characters.</li>
  </ul>
  
  <p>I have written the code, but I am not able to understand why it is not working. Can anyone help?</p>
  
  <p>For example:</p>
  
  <blockquote>
    <p>sentence = "Katie likes to observe nature."</p>
  </blockquote>
  
  <p>It should be transformed to:</p>
  
  <blockquote>
    <p>"Kaie iks t obere ntue*8"</p>
  </blockquote>
  
  <p>However, using my code I get:
  "Katie likes to observe nature*."</p>
  
  <p>Thank you!</p>
  
  <pre><code>public void createEncodedSentence() {
  
      StringBuffer buff = new StringBuffer();
      int counter = 0;
      char a;
  
      for (int i = 0; i &lt; sentence.length(); i++) {
          a = sentence.charAt(i);
  
          if (a == '.') {
              buff.append('*');
          }
          if (a != ' ' &amp;&amp; a != '.') {
              counter++;
          }
          if (counter % 3 == 0) {
              buff.append("");
          }
          buff.append(sentence.charAt(i));
  
  
      }
  
      encodedSentence = buff.toString();
  
  }
  </code></pre>