How do divide the line into equal parts of a defined length?



  • How to cut the line on equal parts/fragments of a certain size?
    A function that can be transferred to any line and indicate the size of the fragment is required. If the line is not divided into equal parts, the latter part may be shorter than the previous.
    For example, for the line 68656c6c6f, we need to get some of it. {"68","65",...}
    How do you do that on C#?



  • using System.IO;
    using System.Linq;
    
    IEnumerable<string> Split(TextReader sr, int size, bool fixedSize = true) {
        while (sr.Peek() >= 0) {
            var buffer = new char[size];
            var c = sr.ReadBlock(buffer, 0, size);
            yield return fixedSize ? new String(buffer) : new String(buffer, 0, c);
        }
    }
    IEnumerable<string> Split(string s, int size, bool fixedSize = true) {
        var sr = new StringReader(s);
        return Split(sr, size, fixedSize);
    }
    

    Example

    var s1 = "68656c6c6f";
    

    var ba = Split(s1, 2) // делим s1 на части
    .Select(s => Convert.ToByte(s, 16)) // конвертируем в байты
    .ToArray();
    var s2 = Encoding.Default.GetString(ba); // "hello"

    Example

    var s1 = "61234";
    var en = Split(s1, 2, false).Select(s => s.PadLeft(2, '0'));
    var s2 = String.Join("; ", en); // "61; 23; 04"

    Rx-based option

    #r "System.Reactive"

    using System.Reactive.Linq;

    var str = "12345";
    foreach (var g in Observable.Buffer(str.ToObservable(), 3).ToEnumerable())
    Console.WriteLine(String.Concat(g));

    result

    123
    45




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2