求用C#,按固定字符长度【中文要计2个】,拆分字符成List。如将字符【712中国人,TSDTS我ES】,每隔4位分割。结果为{"712","中国","人,","TSDT","S我","ES"} 解释:前面3位是因为第4个字符是中文的一半,只能取3位。很头痛,麻烦帮忙。
6条回答 默认 最新
关注using System; using System.Collections.Generic; class Program { static void Main(string[] args) { string str = "712中国人,TSDTS我ES"; int maxLength = 4; List<string> result = SplitString(str, maxLength); foreach (string s in result) { Console.WriteLine(s); } } static List<string> SplitString(string str, int maxLength) { List<string> result = new List<string>(); int length = 0; string temp = ""; foreach (char c in str) { length += GetCharLength(c); if (length <= maxLength) { temp += c; } else { result.Add(temp); temp = c.ToString(); length = GetCharLength(c); } } if (!string.IsNullOrEmpty(temp)) { result.Add(temp); } return result; } static int GetCharLength(char c) { int length = 0; if (c > 127) { length = 2; } else { length = 1; } return length; } }本回答被题主选为最佳回答 , 对您是否有帮助呢?评论 打赏 举报 编辑记录解决 1无用