1. 程式人生 > >C# 如何用長度來切分字串陣列

C# 如何用長度來切分字串陣列

在簡訊切分類似的操作裡, 字串按長度切分非常重要。擴充套件如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Study
{
    public static class Program2
    {
        static void Main(string[] args)
        {
            string[] source = {
                null,
                string.Empty,
                "1234",
                "12345",
                "123456",
                "1234567890",
            };
            int charNum = 5;
            int i = 1;
            foreach (string str in source)
            {
                Console.WriteLine("原字串{0}:{1}", (i++).ToString(), str);
                string[] r = str.SplitByLen(charNum, "{0}/{1}){2}");
                foreach (string s in r)
                {
                    Console.WriteLine("{0}", s);
                }
                Console.WriteLine();
            }
            Console.Read();
        }

        /// <returns></returns>
        /// <summary>
        /// 按字串長度切分成陣列
        /// </summary>
        /// <param name="str">原字串</param>
        /// <param name="separatorCharNum">切分長度</param>
        /// <param name="prefixFormat">字首格式</param>
        /// <returns>字串陣列</returns>
        public static string[] SplitByLen(this string str, int separatorCharNum, string prefixFormat) 
        {
            string[] arr = SplitByLen(str, separatorCharNum);
            if (arr.Length == 1) 
            {
                return arr;
            }
            List<string> list = new List<string>();
            for(int i=1;i<=arr.Length;i++) 
            {
                list.Add(string.Format(prefixFormat,i.ToString(), arr.Length.ToString(), arr[i-1]));
            }
            return list.ToArray();
        }

        /// <summary>
        /// 按字串長度切分成陣列
        /// </summary>
        /// <param name="str">原字串</param>
        /// <param name="separatorCharNum">切分長度</param>
        /// <returns>字串陣列</returns>
        public static string[] SplitByLen(this string str, int separatorCharNum)
        {
            if (string.IsNullOrEmpty(str) || str.Length <= separatorCharNum) 
            {
                return new string[] { str };
            }
            string tempStr = str;
            List<string> strList = new List<string>();
            int iMax = Convert.ToInt32(Math.Ceiling(str.Length / (separatorCharNum * 1.0)));//獲取迴圈次數
            for (int i = 1; i <= iMax; i++)
            {
                string currMsg = tempStr.Substring(0, tempStr.Length > separatorCharNum ? separatorCharNum : tempStr.Length);
                strList.Add(currMsg);
                if (tempStr.Length > separatorCharNum)
                {
                    tempStr = tempStr.Substring(separatorCharNum, tempStr.Length - separatorCharNum);
                }
            }
            return strList.ToArray();
        }
    }
}

結果: