0

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();
Edulo
  • 3
  • 1

3 Answers3

4

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];
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

This might do the trick for you

string animals = "cat98dog75";
string[] DiffAnimals = Regex.Split(animals, "(?<=[0-9]{2})")
                            .Where(s => s != String.Empty) //Just to Remove Empty Entries.
                            .ToArray();
Mohit S
  • 13,723
  • 6
  • 34
  • 69
0

If you want to split the name of the animal and number, try following..

I know its too long....

private static void SplitChars()
    {
        string animals = "cat98dog75";
        Dictionary<string, string> dMyobject = new Dictionary<string, string>();
        string sType = "",sCount = "";
        bool bLastOneWasNum = false;
        foreach (var item in animals.ToCharArray())
        {

            if (char.IsLetter(item))
            {
                if (bLastOneWasNum)
                {
                    dMyobject.Add(sType, sCount);
                    sType = ""; sCount = "";
                    bLastOneWasNum = false;
                }
                sType = sType + item;
            }
            else if (char.IsNumber(item))
            {
                bLastOneWasNum = true;
                sCount = sCount + item;
            }
        }
        dMyobject.Add(sType, sCount);
        foreach (var item in dMyobject)
        {
            Console.WriteLine(item.Key + "- " + item.Value);
        }
    }

You will get output as

cat - 98

dog - 75

Basically, you are getting type and numbers so if you want to use the count, you don't need to split again...

A3006
  • 1,051
  • 1
  • 11
  • 28