KleberBH
KleberBH

Reputation: 462

c# Split string that contains letters and numbers

I need to split a string like this:

string mystring = "A2";
mystring[0] "A" 
mystring[1] "2" 

string mystring = "A11";
mystring[0] "A" 
mystring[1] "11" 

string mystring = "A111";
mystring[0] "A" 
mystring[1] "111" 

string mystring = "AB1";
mystring[0] "AB" 
mystring[1] "1" 

My string always will be letter(s) than number(s), so I need to split it when letters finish. I need to use the number only in this case.

How I can do it? Any suggestion?

Thanks.

Upvotes: 0

Views: 726

Answers (3)

Alex
Alex

Reputation: 21766

You need to use a regular expression to do this:

string[] output = Regex.Matches(mystring, "[0-9]+|[^0-9]+")
.Cast<Match>()
.Select(match => match.Value)
.ToArray();

Upvotes: 1

EZI
EZI

Reputation: 15354

You can use Regex

var parts = Regex.Matches(yourstring, @"\D+|\d+")
            .Cast<Match>()
            .Select(m => m.Value)
            .ToArray();

Upvotes: 1

Ben Jaspers
Ben Jaspers

Reputation: 1546

Regex.Split will do it easily.

string input = "11A";
Regex regex = new Regex("([0-9]+)(.*)");
string[] substrings = regex.Split(input);

Upvotes: 1

Related Questions