title: How can I truncate a string to have at most N characters?
body: <p>The expected approach of <a href="https://doc.rust-lang.org/std/string/struct.String.html#method.truncate" rel="noreferrer"><code>String.truncate(usize)</code></a> fails because it doesn't consider Unicode characters (which is baffling considering Rust treats strings as Unicode).</p>
  
  <pre><code>let mut s = "ボルテックス".to_string();
  s.truncate(4);
  </code></pre>
  
  <blockquote>
    <p>thread '' panicked at 'assertion failed: self.is_char_boundary(new_len)'</p>
  </blockquote>
  
  <p>Additionally, <code>truncate</code> modifies the original string, which is not always desired.</p>
  
  <p>The best I've come up with is to convert to <code>char</code>s and collect into a <code>String</code>.</p>
  
  <pre><code>fn truncate(s: String, max_width: usize) -&gt; String {
      s.chars().take(max_width).collect()
  }
  </code></pre>
  
  <p>e.g.</p>
  
  <pre><code>fn main() {
      assert_eq!(truncate("ボルテックス".to_string(), 0), "");
      assert_eq!(truncate("ボルテックス".to_string(), 4), "ボルテッ");
      assert_eq!(truncate("ボルテックス".to_string(), 100), "ボルテックス");
      assert_eq!(truncate("hello".to_string(), 4), "hell");
  }
  </code></pre>
  
  <p>However this feels very heavy handed.</p>