Get multiple numbers from a string

允我心安 提交于 2019-12-01 12:03:13

This solution will take two first numbers, each can have any number of digits

string s =  "AS_!SD 2453iur ks@d9304-52kasd";

MatchCollection matches = Regex.Matches(s, @"\d+");

string[] result = matches.Cast<Match>()
                         .Take(2)
                         .Select(match => match.Value)
                         .ToArray();

Console.WriteLine( string.Join(Environment.NewLine, result) );

will print

2453
9304

you can parse them to int[] by result.Select(int.Parse).ToArray();

You can loop chars of your string parsing them, if you got a exception thats a letter if not is a number them you must to have a list to add this two numbers, and a counter to limitate this.

follow a pseudocode:

for char in string:

if counter == 2:
 stop loop

if parse gets exception
 continue

else
 loop again in samestring stating this point
 if parse gets exception
  stop loop
 else add char to list

Alternatively you can use the ASCII encoding:

string value = "AS_!SD 2453iur ks@d9304-52kasd";

byte zero = 48; // 0
byte nine = 57; // 9

byte[] asciiBytes = Encoding.ASCII.GetBytes(value);

byte[] asciiNumbers = asciiBytes.Where(b => b >= zero && b <= nine)
                    .ToArray();

char[] numbers = Encoding.ASCII.GetChars(asciiNumbers);

// OR

string numbersString =  Encoding.ASCII.GetString(asciiNumbers);

//First two number from char array
int aNum = Convert.ToInt32(numbers[0]);
int bNum =  Convert.ToInt32(numbers[1]);

//First two number from string
string aString = numbersString.Substring(0,2);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!