Splitting a string into chunks of a certain size

后端 未结 30 1622
时光说笑
时光说笑 2020-11-22 07:55

Suppose I had a string:

string str = \"1111222233334444\"; 

How can I break this string into chunks of some size?

e.g., breaking t

相关标签:
30条回答
  • 2020-11-22 08:18

    An important tip if the string that is being chunked needs to support all Unicode characters.

    If the string is to support international characters like

    0 讨论(0)
  • 2020-11-22 08:19

    Modified (now it accepts any non null string and any positive chunkSize) Konstantin Spirin's solution:

    public static IEnumerable<String> Split(String value, int chunkSize) {
      if (null == value)
        throw new ArgumentNullException("value");
      else if (chunkSize <= 0)
        throw new ArgumentOutOfRangeException("chunkSize", "Chunk size should be positive");
    
      return Enumerable
        .Range(0, value.Length / chunkSize + ((value.Length % chunkSize) == 0 ? 0 : 1))
        .Select(index => (index + 1) * chunkSize < value.Length 
          ? value.Substring(index * chunkSize, chunkSize)
          : value.Substring(index * chunkSize));
    }
    

    Tests:

      String source = @"ABCDEF";
    
      // "ABCD,EF"
      String test1 = String.Join(",", Split(source, 4));
      // "AB,CD,EF"
      String test2 = String.Join(",", Split(source, 2));
      // "ABCDEF"
      String test3 = String.Join(",", Split(source, 123));
    
    0 讨论(0)
  • 2020-11-22 08:20

    I can't remember who gave me this, but it works great. I speed tested a number of ways to break Enumerable types into groups. The usage would just be like this...

    List<string> Divided = Source3.Chunk(24).Select(Piece => string.Concat<char>(Piece)).ToList();
    

    The extention code would look like this...

    #region Chunk Logic
    private class ChunkedEnumerable<T> : IEnumerable<T>
    {
        class ChildEnumerator : IEnumerator<T>
        {
            ChunkedEnumerable<T> parent;
            int position;
            bool done = false;
            T current;
    
    
            public ChildEnumerator(ChunkedEnumerable<T> parent)
            {
                this.parent = parent;
                position = -1;
                parent.wrapper.AddRef();
            }
    
            public T Current
            {
                get
                {
                    if (position == -1 || done)
                    {
                        throw new InvalidOperationException();
                    }
                    return current;
    
                }
            }
    
            public void Dispose()
            {
                if (!done)
                {
                    done = true;
                    parent.wrapper.RemoveRef();
                }
            }
    
            object System.Collections.IEnumerator.Current
            {
                get { return Current; }
            }
    
            public bool MoveNext()
            {
                position++;
    
                if (position + 1 > parent.chunkSize)
                {
                    done = true;
                }
    
                if (!done)
                {
                    done = !parent.wrapper.Get(position + parent.start, out current);
                }
    
                return !done;
    
            }
    
            public void Reset()
            {
                // per http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.reset.aspx
                throw new NotSupportedException();
            }
        }
    
        EnumeratorWrapper<T> wrapper;
        int chunkSize;
        int start;
    
        public ChunkedEnumerable(EnumeratorWrapper<T> wrapper, int chunkSize, int start)
        {
            this.wrapper = wrapper;
            this.chunkSize = chunkSize;
            this.start = start;
        }
    
        public IEnumerator<T> GetEnumerator()
        {
            return new ChildEnumerator(this);
        }
    
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    
    }
    private class EnumeratorWrapper<T>
    {
        public EnumeratorWrapper(IEnumerable<T> source)
        {
            SourceEumerable = source;
        }
        IEnumerable<T> SourceEumerable { get; set; }
    
        Enumeration currentEnumeration;
    
        class Enumeration
        {
            public IEnumerator<T> Source { get; set; }
            public int Position { get; set; }
            public bool AtEnd { get; set; }
        }
    
        public bool Get(int pos, out T item)
        {
    
            if (currentEnumeration != null && currentEnumeration.Position > pos)
            {
                currentEnumeration.Source.Dispose();
                currentEnumeration = null;
            }
    
            if (currentEnumeration == null)
            {
                currentEnumeration = new Enumeration { Position = -1, Source = SourceEumerable.GetEnumerator(), AtEnd = false };
            }
    
            item = default(T);
            if (currentEnumeration.AtEnd)
            {
                return false;
            }
    
            while (currentEnumeration.Position < pos)
            {
                currentEnumeration.AtEnd = !currentEnumeration.Source.MoveNext();
                currentEnumeration.Position++;
    
                if (currentEnumeration.AtEnd)
                {
                    return false;
                }
    
            }
    
            item = currentEnumeration.Source.Current;
    
            return true;
        }
    
        int refs = 0;
    
        // needed for dispose semantics 
        public void AddRef()
        {
            refs++;
        }
    
        public void RemoveRef()
        {
            refs--;
            if (refs == 0 && currentEnumeration != null)
            {
                var copy = currentEnumeration;
                currentEnumeration = null;
                copy.Source.Dispose();
            }
        }
    }
    /// <summary>Speed Checked.  Works Great!</summary>
    public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> source, int chunksize)
    {
        if (chunksize < 1) throw new InvalidOperationException();
    
        var wrapper = new EnumeratorWrapper<T>(source);
    
        int currentPos = 0;
        T ignore;
        try
        {
            wrapper.AddRef();
            while (wrapper.Get(currentPos, out ignore))
            {
                yield return new ChunkedEnumerable<T>(wrapper, chunksize, currentPos);
                currentPos += chunksize;
            }
        }
        finally
        {
            wrapper.RemoveRef();
        }
    }
    #endregion
    
    0 讨论(0)
  • 2020-11-22 08:22

    Using regular expressions and Linq:

    List<string> groups = (from Match m in Regex.Matches(str, @"\d{4}")
                           select m.Value).ToList();
    

    I find this to be more readable, but it's just a personal opinion. It can also be a one-liner : ).

    0 讨论(0)
  • 2020-11-22 08:23

    I took this to another level. Chucking is an easy one liner, but in my case I needed whole words as well. Figured I would post it, just in case someone else needs something similar.

    static IEnumerable<string> Split(string orgString, int chunkSize, bool wholeWords = true)
    {
        if (wholeWords)
        {
            List<string> result = new List<string>();
            StringBuilder sb = new StringBuilder();
    
            if (orgString.Length > chunkSize)
            {
                string[] newSplit = orgString.Split(' ');
                foreach (string str in newSplit)
                {
                    if (sb.Length != 0)
                        sb.Append(" ");
    
                    if (sb.Length + str.Length > chunkSize)
                    {
                        result.Add(sb.ToString());
                        sb.Clear();
                    }
    
                    sb.Append(str);
                }
    
                result.Add(sb.ToString());
            }
            else
                result.Add(orgString);
    
            return result;
        }
        else
            return new List<string>(Regex.Split(orgString, @"(?<=\G.{" + chunkSize + "})", RegexOptions.Singleline));
    }
    
    0 讨论(0)
  • 2020-11-22 08:24
    static IEnumerable<string> Split(string str, int chunkSize)
    {
        return Enumerable.Range(0, str.Length / chunkSize)
            .Select(i => str.Substring(i * chunkSize, chunkSize));
    }
    

    Please note that additional code might be required to gracefully handle edge cases (null or empty input string, chunkSize == 0, input string length not divisible by chunkSize, etc.). The original question doesn't specify any requirements for these edge cases and in real life the requirements might vary so they are out of scope of this answer.

    0 讨论(0)
提交回复
热议问题