如何从字符串中获取数字

我想从字符串中获取数字,例如: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将其转换为整数。

你可以采用正则表达方式。 这通常比循环通过字符串更快

  public int GetNumber(string text) { var exp = new Regex("(\d+)"); // find a sequence of digits could be \d+ var matches = exp.Matches(text); if (matches.Count == 1) // if there's one number return that { int number = int.Parse(matches[0].Value); return number } else if (matches.Count > 1) throw new InvalidOperationException("only one number allowed"); else return 0; } 

循环遍历字符串中的每个字符并测试它是否为数字。 删除所有非数字然后你有一个简单的整数作为字符串。 然后你可以使用int.parse。

 string numString; foreach(char c in inputString) if (Char.IsDigit(c)) numString += c; int realNum = int.Parse(numString); 

你可以做这样的事情,然后它也可以使用多个数字

 public IEnumerable GetNumbers(string indata) { MatchCollection matches = Regex.Matches(indata, @"\d+"); foreach (Match match in matches) { yield return match.Value; } } 

首先用“数字”(整数?long?decimal?double?)和“从字符串中获取数字”来写出你的意思。 包括你想要处理的所有情况(前导/尾随标志?文化不变的千位/小数分隔符,文化敏感的千位/小数分隔符,非常大的值,不包含有效数字的字符串,…… )。

然后为每个需要能够处理的案例编写一些unit testing。

然后编写方法代码(应该很简单 – 基本上从字符串中提取数字位,并尝试解析它。到目前为止提供的一些答案将适用于整数,前提是字符串不包含大于Int32.MaxValue的值) 。