title: Truncating Strings by Bytes
body: <p>I create the following for truncating a string in java to a new string with a given number of bytes. </p>
  
  <pre><code>        String truncatedValue = "";
          String currentValue = string;
          int pivotIndex = (int) Math.round(((double) string.length())/2);
          while(!truncatedValue.equals(currentValue)){
              currentValue = string.substring(0,pivotIndex);
              byte[] bytes = null;
              bytes = currentValue.getBytes(encoding);
              if(bytes==null){
                  return string;
              }
              int byteLength = bytes.length;
              int newIndex =  (int) Math.round(((double) pivotIndex)/2);
              if(byteLength &gt; maxBytesLength){
                  pivotIndex = newIndex;
              } else if(byteLength &lt; maxBytesLength){
                  pivotIndex = pivotIndex + 1;
              } else {
                  truncatedValue = currentValue;
              }
          }
          return truncatedValue;
  </code></pre>
  
  <p>This is the first thing that came to my mind, and I know I could improve on it. I saw another post that was asking a similar question there, but they were truncating Strings using the bytes instead of String.substring. I think I would rather use String.substring in my case. </p>
  
  <p>EDIT: I just removed the UTF8 reference because I would rather be able to do this for different storage types aswell.</p>