【问题标题】:How to get number from a string如何从字符串中获取数字
【发布时间】:2010-02-08 12:52:49
【问题描述】:

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

提前致谢。

【问题讨论】:

  • 如果字符串包含123my456number78怎么办?
  • 尝试搜索 .NET TryParse
  • 当字符串为 "Test123again67" 时你期望会发生什么?
  • @anthares , Winston 在我的情况下,实际上没有这样的输入,数字总是在字符之间。但我认为如果它适用于那些它应该也适用于我的情况,它也可能对其他人有帮助。

标签: c# .net vb.net string


【解决方案1】:

如果字符串中只有一个数字,并且它是一个整数,那么是这样的:

 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 将其转换为整数。

【讨论】:

【解决方案2】:

你可以采用正则表达式的方式。这通常比遍历字符串要快

        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;
        }

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 你必须先初始化 numString (numString = "")。
    • 'vb implementation Dim numString As String="0" For Each c As Char In inputString If [Char].IsDigit(c) Then numString += c End If Next Dim realNum As Integer = Integer.解析(numString)
    • 字符串 numString="0";初始化很好,如果没有数字,它会给出 0
    • 在像 the23foo42 这样的格式错误的输入的情况下,这将返回 2342,而一个例外是合适的,因为这是一种特殊情况,并且规范无法知道返回什么
    • @Thunder:很好,喜欢将 init 设置为“0”的想法。
    【解决方案4】:

    你可以这样做,然后它也可以处理多个数字

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

    【讨论】:

    • match.Value 是一个字符串,为什么要转换成字符串呢?
    • 好点,没必要。当我写回复时,我知道 Value 将是一个对象,我更新了回复以反映这一点。感谢您指出这一点。
    【解决方案5】:

    首先编写一个规范,说明“数字”(整数?长?小数?双精度?)和“从字符串中获取数字”的含义。包括您希望能够处理的所有情况(前导/尾随符号?文化不变的千位/小数分隔符,文化敏感的千位/小数分隔符,非常大的值,不包含有效数字的字符串,... )。

    然后为您需要能够处理的每个案例编写一些单元测试。

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

    【讨论】:

    • +1 不知道这些是不可能正确回答这个问题的。
    猜你喜欢
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    相关资源
    最近更新 更多