-1

What's the most efficient way to split string values into an array every specified number of times? For example, split by 2:

string test = "12345678";

To:

string[] test = new[] {"12", "34", "56"};

What I've tried:

double part = 2;
int k = 0;
var test = bin.ToLookup(c => Math.Floor(k++ / part)).Select(e => new string(e.ToArray()));
Wes
  • 1,847
  • 1
  • 16
  • 30
  • 3
    All that has been posted is a program description. However, we need you to ask a question according to the [ask] page. We can't be sure what you want from us. Please [edit] your post to include a valid question that we can answer. Reminder: make sure you know what is on-topic here by visiting the [help/on-topic]; **asking us to write the program for you**, suggestions, and external links are **off-topic**. – Patrick Artner Feb 11 '20 at 09:26
  • 1
    @rup - yep, and no research is presented, no solution was tried, no code was shown, no effort was spent. – Patrick Artner Feb 11 '20 at 09:27
  • Most-efficient is not considered as a good question, because it really needs comparison between different solutions and maybe even benchmarking. – Reza Aghaei Feb 11 '20 at 09:38
  • 1
    OK, removed my answer and closed the question because there is a good duplicate sharing some good options to split the string by chunks. – Reza Aghaei Feb 11 '20 at 09:43
  • 1
    @RezaAghaei That's fine, that link was useful. – Wes Feb 11 '20 at 09:52

1 Answers1

0

You can use LINQ : when length was the length of part

var str = "12345678";
var length = 2;
var result = Enumerable.Range(0, (str.Length + length - 1) / length)
.Select(i => str.Substring(i * length, Math.Min(str.Length - i *length, 
length)));
Marwen Jaffel
  • 703
  • 1
  • 6
  • 14