Kye
Kye

Reputation: 107

Split string in places where digits change to letters and vice versa

I'm looking for better solution for my problem.
I have string that contains digits and letters only e.g. "123blue321car" and i want to split it into list ( "123","blue","321","car").

I have pretty bad solution : Iterate through string, add comma and later to use .Split() with comma as delimiter. But I wonder if is it good ? Is there better idea to deal with it ?

Upvotes: 0

Views: 64

Answers (1)

Mark
Mark

Reputation: 5239

You could use a regex to split your string, below is an example:

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(\d+|\D+)";
        string input = @"123blue321car";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

Upvotes: 2

Related Questions