Source: https://codereview.stackexchange.com/a/55114
void Main() { const string Input = "a\u0304\u0308bc\u0327"; var bytes = Encoding.UTF8.GetByteCount(Input); Console.WriteLine("{0} ({1} bytes in UTF-8)", Input, bytes); for (var i = 0; i <= bytes; i++) { var result = LimitBytes(Input, Encoding.UTF8, i); Console.WriteLine("{0} \"{1}\" {2}", i, result, Input.StartsWith(result, StringComparison.Ordinal)); } } public static string LimitBytes(string input, Encoding encoding, int maxBytes) { if (maxBytes == 0 || string.IsNullOrEmpty(input)) return string.Empty; if (encoding.GetByteCount(input) <= maxBytes) return input; var sb = new StringBuilder(); var bytes = 0; foreach (char c in input) { bytes += encoding.GetByteCount(c.ToString()); if (bytes > maxBytes) break; sb.Append(c); } return sb.ToString(); } /* OUTPUT: ā̈bç (9 bytes in UTF-8) 0 "" True 1 "a" True 2 "a" True 3 "ā" True 4 "ā" True 5 "ā̈" True 6 "ā̈b" True 7 "ā̈bc" True 8 "ā̈bc" True 9 "ā̈bç" True */
487100cookie-checkLimit String By Byte Count