TyGerX
TyGerX

Reputation: 573

Take only numbers from string and put in an array

ok i found this for removing all 'junk' that is not a number from a string

TextIN = " 0 . 1 ,2 ; 3 4 -5 6 ,7 ,8; 9 "

string justNumbers = new String(textIN.Where(Char.IsDigit).ToArray());

= "0123456789"

this removes all "junk" from my string leaving me just the numbers, but still how i can modify this , so i can have at least one delimiter for example a ' , ' b etween my numbers like "0,1,2,3,4,5,6,7,8,9" because i need to delimit this number so i can put them in an array of ints and work with them and there are not always just one digit numbers i may have 105 , 85692 etc.. any help please ?!

Upvotes: 3

Views: 3655

Answers (4)

jCoder
jCoder

Reputation: 2319

You can also convert to numeric values like this:

int[] numbers = Regex.Matches(textIN, "(-?[0-9]+)").OfType<Match>().Select(m => int.Parse(m.Value)).ToArray();

@L.B: agreed, but nthere might be negative values, too.

Upvotes: 6

L.B
L.B

Reputation: 116178

For n digit numbers you can use regex.

string s = String.Join(",",
                  Regex.Matches(textIN,@"\d+").Cast<Match>().Select(m=>m.Value));

Upvotes: 1

scarecrow198504
scarecrow198504

Reputation: 108

string justNumbers = new String(textIN.Where(Char.IsDigit).ToArray()); = "0123456789"
string[] words = justNumbers.Split(',');

will seperate the string into an array of numbers, delimited by commas.

Upvotes: 0

ionden
ionden

Reputation: 12786

string test = string.Join(",", textIN.Where(Char.IsDigit));

Upvotes: 1

Related Questions