sowinworkTwo 2023-10-31 12:27 采纳率: 100%
浏览 19
已结题

C#按固定字符长度分割成数列

求用C#,按固定字符长度【中文要计2个】,拆分字符成List。如将字符【712中国人,TSDTS我ES】,每隔4位分割。结果为{"712","中国","人,","TSDT","S我","ES"} 解释:前面3位是因为第4个字符是中文的一半,只能取3位。很头痛,麻烦帮忙。

  • 写回答

6条回答 默认 最新

  • 专家-赤兔[在线] 优质创作者: 编程框架技术领域 2023-10-31 12:27
    关注
    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;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(5条)

报告相同问题?

问题事件

  • 系统已结题 11月8日
  • 已采纳回答 10月31日
  • 创建了问题 10月31日