title: Wrap the string after a number of characters word-wise in Java
body: <p>I have this code:</p>
  
  <pre><code>    String s = "A very long string containing " +
                     "many many words and characters. " +
                     "Newlines will be entered at spaces.";
  
      StringBuilder sb = new StringBuilder(s);
  
      int i = 0;
      while ((i = sb.indexOf(" ", i + 20)) != -1) {
          sb.replace(i, i + 1, "\n");
      }
  
      System.out.println(sb.toString());
  </code></pre>
  
  <p>The output of the code is:</p>
  
  <pre><code>A very long string containing
  many many words and
  characters. Newlines
  will be entered at spaces.
  </code></pre>
  
  <p>The above code is wrapping the string after the next space of every 30 characters, but I need to wrap the string after the previous space of every 30 characters, like for the first line it will be:</p>
  
  <p><code>A very long string</code></p>
  
  <p>And the 2nd line will be</p>
  
  <pre><code>containing many
  </code></pre>
  
  <p>Please give some proper solution.</p>