Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

regex

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.

like image 525
Addie Avatar asked Mar 02 '10 09:03

Addie


People also ask

How do I split a string into another string?

Bookmark this question. Show activity on this post. I've been using the Split() method to split strings, but this only appears to work if you are splitting a string by a character.

How do you split string values?

Split() Method in C# with Examples. In C#, Split() is a string class method. The Split() method returns an array of strings generated by splitting of original string separated by the delimiters passed as a parameter in Split() method. The delimiters can be a character or an array of characters or an array of strings.

What is a delimiter in C?

In computer programming, a delimiter is a character that identifies the beginning or the end of a character string (a contiguous sequence of characters).

What is strtok function in C?

strtok() Method: Splits str[] according to given delimiters and returns the next token. It needs to be called in a loop to get all tokens. It returns NULL when there are no more tokens.


2 Answers

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);
like image 97
Konrad Rudolph Avatar answered Nov 15 '22 15:11

Konrad Rudolph


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);
}
like image 26
Sergej Andrejev Avatar answered Nov 15 '22 16:11

Sergej Andrejev