Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split a string with max character limit

Tags:

c#

I'm attempting to split a string into many strings (List) with each one having a maximum limit of characters. So say if I had a string of 500 characters, and I want each string to have a max of 75, there would be 7 strings, and the last one would not have a full 75.

I've tried some of the examples I have found on stackoverflow, but they 'truncate' the results. Any ideas?

like image 936
Ciel Avatar asked Dec 22 '22 02:12

Ciel


2 Answers

You can write your own extension method to do something like that

static class StringExtensions
{
    public static IEnumerable<string> SplitOnLength(this string input, int length)
    {
        int index = 0;
        while (index < input.Length)
        {
            if (index + length < input.Length)
                yield return input.Substring(index, length);
            else
                yield return input.Substring(index);

            index += length;
        }
    }
}

And then you could call it like this

string temp = new string('@', 500);

string[] array = temp.SplitOnLength(75).ToArray();

foreach (string x in array)
    Console.WriteLine(x);
like image 122
Anthony Pegram Avatar answered Jan 02 '23 16:01

Anthony Pegram


I think this is a little cleaner than the other answers:

    public static IEnumerable<string> SplitByLength(string s, int length)
    {
        while (s.Length > length)
        {
            yield return s.Substring(0, length);
            s = s.Substring(length);
        }

        if (s.Length > 0) yield return s;            
    }
like image 28
Jay Bazuzi Avatar answered Jan 02 '23 17:01

Jay Bazuzi