简体   繁体   中英

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?!

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();

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

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

For n digit numbers you can use regex.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM