Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a long string into an array of shorter strings

Tags:

c#

How can I split a string of around 300 (n) words into an array of n/30 strings of 30 words?

like image 204
Meir Avatar asked Jan 29 '26 08:01

Meir


2 Answers

You can use Regex.Matches:

string[] bits = Regex.Matches(input, @"\w+(?:\W+\w+){0,29}")
                     .Cast<Match>()
                     .Select(match => match.Value)
                     .ToArray();

See it working online: ideone

like image 128
Mark Byers Avatar answered Jan 30 '26 21:01

Mark Byers


A Regex split would make sense if you have a very large or a very small of characters that can be a part of your string. Alternatively, you can use the Substring method of the String class to get the desired result:

        string input = "abcdefghijklmnopqrstuvwxyz";
        const int INTERVAL = 5;

        List<string> lst = new List<string>();
        int i = 0;
        while (i < input.Length)
        {
            string sub = input.Substring(i, i + INTERVAL < input.Length ? INTERVAL : input.Length - i);
            Console.WriteLine(sub);
            lst.Add(sub);
            i += INTERVAL;
        }
like image 33
NeerajH Avatar answered Jan 30 '26 21:01

NeerajH