Addie
Addie

Reputation: 1691

How do I split a string in C# based on letters and numbers

How can I split a string such as "Mar10" into "Mar" and "10" in c#? The format of the string will always be letters then numbers so I can use the first instance of a number as an indicator for where to split the string.

Upvotes: 14

Views: 15531

Answers (4)

Dominic Giallombardo
Dominic Giallombardo

Reputation: 955

var match = Regex.Match(yourString, "([|A-Z|a-z| ]*)([\d]*)");
var month = match.Groups[1].Value;
var day = int.Parse(match.Groups[2].Value);

I tried Konrad's answer above, but it didn't quite work when I entered it into RegexPlanet. Also the Groups[0] returns the whole string Mar10. You want to start with Groups[1], which should return Mar and Groups[2] should return 10.

Upvotes: 5

Sergej Andrejev
Sergej Andrejev

Reputation: 9403

You are not saying it directly, but from your example it seems are you just trying to parse a date.

If that's true, how about this solution:

DateTime date;
if(DateTime.TryParseExact("Mar10", "MMMdd", new CultureInfo("en-US"), DateTimeStyles.None, out date))
{
    Console.WriteLine(date.Month);
    Console.WriteLine(date.Day);
}

Upvotes: 6

sashaeve
sashaeve

Reputation: 9607

char[] array = "Mar10".ToCharArray();
int index = 0;
for(int i=0;i<array.Length;i++)
{
   if (Char.IsNumber(array[i]){
      index = i;
      break;
   }
}

Index will indicate split position.

Upvotes: 3

Konrad Rudolph
Konrad Rudolph

Reputation: 545528

You could do this:

var match = Regex.Match(yourString, "(\w+)(\d+)");
var month = match.Groups[0].Value;
var day = int.Parse(match.Groups[1].Value);

Upvotes: 20

Related Questions