zoukankan      html  css  js  c++  java
  • C#中 以固定长度 取字符串中的数据

    1)//使用指定步长走完字符串

    //比如 把int数组通过","分割成为字符串。然后每次读取四位,直到读取全部字符串。

    public static void testforeachArray() {
            int[] ins = { 1,2,3,4,5,6,7,8,9};
            string inStr = string.Join(",", ins);
            Console.WriteLine(inStr);
            int count = 4;
            int length = (int)Math.Ceiling((double)inStr.Length / count);        
            Console.WriteLine(length);  // 5
            for (int i = 0; i < length; i++)
            {
                int start = count * i;
                //int end = start + count - 1;
                count = i == length-1 ? inStr.Length-i*count : count;
                Console.WriteLine(inStr.Substring(start,count));
            }
        }
    

    结果:
    1,2,3,4,5,6,7,8,9
    5
    1,2,
    3,4,
    5,6,
    7,8,
    9

    2)使用指定步长 通过GetRange 读取List中数据

            int[] ins = { 1,2,3,4,5,6,7,8,9};
            string inStr = string.Join(",", ins);
            int range = 3; //指定步长
            List<string> senddata = new List<string>();
            List<string> arraydata = inStr.Split(',').ToList<string>();
            for (int i=0;i<arraydata.Count;i=i+range) 
            {
                int index = i;
                //(index + range)为 当前执行的index加上执行步长,如果小于总数据长度就是默认步长range,如果大于等于就是 总和减去当前执行到的index
                int counts = (index + range) < arraydata.Count ? range : (arraydata.Count - index);
    
                List<string> datas = arraydata.GetRange(index, counts);
                Console.WriteLine(string.Join("|",datas));
            }
    

    结果 :
    1|2|3
    4|5|6
    7|8|9

  • 相关阅读:
    Interesting Finds: 2008.09.15~2008.09.21
    Interesting Finds: 2008.10.05~2008.10.07
    Interesting Find: 2008.10.02
    Interesting Finds: 2008.10.13~2008.10.15
    Interesting Finds: 2008.09.29
    Interesting Finds: 2008.10.08~2008.10.09
    Interesting Finds: 2008.09.22~2008.09.27
    Interesting Finds: 2008.10.12
    Interesting Finds: 2008.10.16~2008.10.18
    9月27号
  • 原文地址:https://www.cnblogs.com/sunny3158/p/15087162.html
Copyright © 2011-2022 走看看