如何从一个字符串获取数 [英] How to get number from a string

查看:109
本文介绍了如何从一个字符串获取数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个字符串,例如获得数:
My123number给123
同样VARCHAR(32)给出32等

I would like to get number from a string eg: My123number gives 123 Similarly varchar(32) gives 32 etc

谢谢进展。

推荐答案

如果有将只有一个埋在字符串中的数字,它是将是一个整数,然后是这样的:

If there is going to be only one number buried in the string, and it is going to be an integer, then something like this:

 int n;
 string s = "My123Number";
 if (int.TryParse (new string (s.Where (a => Char.IsDigit (a)).ToArray ()), out n)) {
    Console.WriteLine ("The number is {0}", n);
 }

要解释一下: s.Where(A => ; Char.IsDigit(A))ToArray的()提取只从原始字符串中的数字转换成char数组。然后,新字符串的转换为字符串,最后 int.TryParse 的转换为整数。

To explain: s.Where (a => Char.IsDigit (a)).ToArray () extracts only the digits from the original string into an array of char. Then, new string converts that to a string and finally int.TryParse converts that to an integer.

这篇关于如何从一个字符串获取数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆