title: Truncating unicode so it fits a maximum size when encoded for wire transfer
body: <p>Given a Unicode string and these requirements:</p>
  
  <ul>
  <li>The string be encoded into some byte-sequence format (e.g. UTF-8 or JSON unicode escape)</li>
  <li>The encoded string has a maximum length</li>
  </ul>
  
  <p>For example, the iPhone push service requires JSON encoding with a maximum total packet size of 256 bytes.</p>
  
  <p><strong>What is the best way to truncate the string so that it re-encodes to valid Unicode and that it displays reasonably correctly?</strong></p>
  
  <p>(Human language comprehension is not necessary&mdash;the truncated version can look odd e.g. for an orphaned combining character or a Thai vowel, just as long as the software doesn't crash when handling the data.)</p>
  
  <p>See Also:</p>
  
  <ul>
  <li>Related Java question: <a href="https://stackoverflow.com/questions/119328/">How do I truncate a java string to fit in a given number of bytes, once UTF-8 encoded?</a></li>
  <li>Related Javascript question: <a href="https://stackoverflow.com/questions/1515884/">Using JavaScript to truncate text to a certain size</a></li>
  </ul>