title: What is most optimal way to truncate a string to limit its length?
body: <p>I am writing a function to limit the length of a sentence. Say limit is 15, and the sentence is &quot;SO is great website&quot;. I don't want to truncate it exactly at the 15th position, otherwise the truncated sentence would become &quot;SO is great web&quot;. But, what I want to do is to truncate from the first space before the limit. It would give me &quot;SO is great&quot;.</p>
  <p>One way of doing it is</p>
  <blockquote>
  <p>int firstIndexOfSpaceBeforeGIvenIndex= str.lastIndexOf(&quot; &quot;, 15);</p>
  <p>str = StringUtils.truncate(str, 0, firstIndexOfSpaceBeforeGIvenIndex);</p>
  </blockquote>
  <p>The string could be very long and I have to perform this operation on thousands of strings. So performance is my concern. What is the most optimal way to achieve this task?</p>