Edulo Edulo - 4 years ago 104
C# Question

String Split to String Array without seperator

Code:

string animals = "cat98dog75";


What i try to achieve :


string a = "cat98";

string b = "dog75";


Question :

How do i split the string using some range delimiter?

example :

animals.split();

Answer Source

I suggest matching with a help of regular expressions:

  using System.Text.RegularExpressions;
  ...

  string animals = "cat98dog75";

  string[] items = Regex
    .Matches(animals, "[a-zA-Z]+[0-9]*")
    .OfType<Match>()
    .Select(match => match.Value)
    .ToArray();

  string a = items[0];
  string b = items[1];

  Concole.Write(string.Join(", ", items));

Outcome:

  cat98, dog75

In case you want to split the initial string by equal size chunks:

  int size = 5;

  string[] items = Enumerable
    .Range(0, animals.Length / size + (animals.Length % size > 0 ? 1 : 0))
    .Select(index => (index + 1) * size <= animals.Length
       ? animals.Substring(index * size, size)
       : animals.Substring(index * size))
    .ToArray();

  string a = items[0];
  string b = items[1];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download