// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Text; namespace E { public class Program { // http://stackoverflow.com/questions/12411142/substring-utf-8-for-both-latin-chinese-cyrilic-etc public static string SubstringWithinUtf8Limit(string text, int byteLimit) { int byteCount = 0; char[] buffer = new char[1]; for (int i = 0; i < text.Length; i++) { buffer[0] = text[i]; byteCount += Encoding.UTF8.GetByteCount(buffer); if (byteCount > byteLimit) { return text.Substring(0, i); } } return text; } // alternative public static string SubstringWithinUtf8LimitAlt(string text, int byteLimit) { /* byte[] buf = Encoding.UTF8.GetBytes(text.ToCharArray(), 0, byteLimit); if(buf.Length <= byteLimit) return text; int ix = byteLimit; while((buf[ix] & 0xC) != 0) ix--; return Encoding.UTF8.GetString(buf, 0, ix); */ int len = 0; for(int i = 0; i < text.Length; i++) { if(text[i] <= 0x007F) { len += 1; } else if(text[i] <= 0x07FF) { len += 2; } else if(text[i] <= 0x0000FFFF) { len += 3; } if(len > byteLimit) { return text.Substring(0, i); } } return null; } public static void Test(string s, int len) { string s1 = SubstringWithinUtf8Limit(s, len); Console.WriteLine("SO: " + s1.Length + " " + Encoding.UTF8.GetByteCount(s1)); string s2 = SubstringWithinUtf8LimitAlt(s, len); Console.WriteLine("AV: " + s2.Length + " " + Encoding.UTF8.GetByteCount(s2)); } public static void Test2(int rep, int len) { string s1 = "".PadRight(len+1, 'A'); string s2 = "".PadRight(len+1, '�'); DateTime dt1 = DateTime.Now; for(int i = 0; i < rep; i++) { SubstringWithinUtf8Limit(s1, len); SubstringWithinUtf8Limit(s2, len); } DateTime dt2 = DateTime.Now; Console.WriteLine("SO: " + (dt2-dt1).TotalSeconds); DateTime dt3 = DateTime.Now; for(int i = 0; i < rep; i++) { SubstringWithinUtf8LimitAlt(s1, len); SubstringWithinUtf8LimitAlt(s2, len); } DateTime dt4 = DateTime.Now; Console.WriteLine("AV: " + (dt4-dt3).TotalSeconds); } private const int N = 10000000; public static void Main(string[] args) { Test("ABCDEFGHIJ", 6); Test("����������", 6); Test("AA�AA�AA�A", 6); Test("AA�AA�AA�A", 5); Test("AA�AA�AA�A", 4); Test("A�AA�AA�AA", 6); Test("A�AA�AA�AA", 5); Test("A�AA�AA�AA", 4); Test("\u1111\u1111\u1111\u1111\u1111\u1111\u1111\u1111\u1111\u1111\u1111\u1111\u1111\u1111\u1111\u1111", 6); Test2(N/10, 10); Test2(N/100, 100); Test2(N/1000, 1000); } } }