Split String into smaller Strings by length variable

前端 未结 12 1940
谎友^
谎友^ 2020-12-01 07:19

I\'d like to break apart a String by a certain length variable.
It needs to bounds check so as not explode when the last section of string is not as long as or longer th

12条回答
  •  执念已碎
    2020-12-01 08:04

    Yet another slight variant (classic but simple and pragmatic):

    class Program
    {
        static void Main(string[] args) {
            string msg = "AAABBBCC";
    
            string[] test = msg.SplitByLength(3);            
        }
    }
    
    public static class SplitStringByLength
    {
        public static string[] SplitByLength(this string inputString, int segmentSize) {
            List segments = new List();
    
            int wholeSegmentCount = inputString.Length / segmentSize;
    
            int i;
            for (i = 0; i < wholeSegmentCount; i++) {
                segments.Add(inputString.Substring(i * segmentSize, segmentSize));
            }
    
            if (inputString.Length % segmentSize != 0) {
                segments.Add(inputString.Substring(i * segmentSize, inputString.Length - i * segmentSize));
            }
    
            return segments.ToArray();
        }
    }
    

提交回复
热议问题