c# - 如何从字符串中获取数字

标签 c# .net vb.net string

我想从字符串中获取数字,例如: My123number 给出 123 同样 varchar(32) 给出 32 等

提前致谢。

最佳答案

如果字符串中只有一个数字,并且是一个整数,则如下所示:

 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数组中。然后,new string 将其转换为字符串,最后 int.TryParse 将其转换为整数。

关于c# - 如何从字符串中获取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2221629/

相关文章:

c# - 如何为单元测试在进程中创建 ServicedComponent 实例?

c# - 在不锁定集合的情况下从通用集合中获取 Count 值是安全的吗?

c# - List<T>.IndexOf() 如何对自定义对象进行比较?

.net - 启动部署的我的应用程序会出现 “has stopped working”错误。我该如何调试?

vb.net - 为什么 VB.Net 类型推断在类字段中不起作用?

c# - 如何在 F# 中实例化类及其属性

c# - C# 中的通用输入参数?

c# - 将 C# 6.0 默认属性值转换为 C# 5.0

c# - 哈希速度 - 神秘的结果(哈希两次比哈希一次慢得多)

vb.net - 从 VB.NET 中的 List(Of T) 引发事件