简体   繁体   English

只从字符串中取出数字并放入数组中

[英]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" =“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?!这会从我的字符串中删除所有“垃圾”,只留下数字,但我仍然可以修改它,所以我可以至少有一个分隔符,例如 a ', ' b 在我的数字之间,如 "0,1,2,3 ,4,5,6,7,8,9" 因为我需要分隔这个数字所以我可以把它们放在一个整数数组中并使用它们并且并不总是只有一个数字我可能有 105、85692 等.. 有什么帮助吗?!

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. @LB:同意,但也可能有负值。

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

For n digit numbers you can use regex.对于 n 位数字,您可以使用正则表达式。

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.将字符串分隔成一个数字数组,用逗号分隔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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