On Windows Phone, I want to fine-tune any given string to the equivalent of 100 ASCII characters in length.
String.Length is clearly useless since the Chinese string uses 3 bytes per character, the Danish string uses 2 or 4 bytes per character, and the Russian string uses 4 bytes per character.
The only encoding available is UTF-8 and UTF-16. So what should I do?
The idea is this:
private static string UnicodeSubstring(string text, int length) { var bytes = Encoding.UTF8.GetBytes(text); return Encoding.UTF8.GetString(bytes, 0, Math.Min(bytes.Length, length)); }
But the length must be correctly divided by the number of bytes used for each character, so the last character is always displayed correctly.
source share