Split a long string into an array of shorter strings

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

+3
source share
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 how it works on the Internet: ideone

+7
source

and a regex split will make sense if you have very large or very small characters that can be 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;
        }
+2
source

Source: https://habr.com/ru/post/1747883/


All Articles