Find and extract a number from a string

前端 未结 29 2630
温柔的废话
温柔的废话 2020-11-22 03:19

I have a requirement to find and extract a number contained within a string.

For example, from these strings:

string test = \"1 test\"
string test1 =         


        
相关标签:
29条回答
  • 2020-11-22 04:00
    var outputString = String.Join("", inputString.Where(Char.IsDigit));
    

    Get all numbers in the string. So if you use for examaple '1 plus 2' it will get '12'.

    0 讨论(0)
  • 2020-11-22 04:00

    here is my solution

    string var = "Hello345wor705Ld";
    string alpha = string.Empty;
    string numer = string.Empty;
    foreach (char str in var)
    {
        if (char.IsDigit(str))
            numer += str.ToString();
        else
            alpha += str.ToString();
    }
    Console.WriteLine("String is: " + alpha);
    Console.WriteLine("Numeric character is: " + numer);
    Console.Read();
    
    0 讨论(0)
  • 2020-11-22 04:00
    string s = "kg g L000145.50\r\n";
            char theCharacter = '.';
            var getNumbers = (from t in s
                              where char.IsDigit(t) || t.Equals(theCharacter)
                              select t).ToArray();
            var _str = string.Empty;
            foreach (var item in getNumbers)
            {
                _str += item.ToString();
            }
            double _dou = Convert.ToDouble(_str);
            MessageBox.Show(_dou.ToString("#,##0.00"));
    
    0 讨论(0)
  • 2020-11-22 04:02
     string input = "Hello 20, I am 30 and he is 40";
     var numbers = Regex.Matches(input, @"\d+").OfType<Match>().Select(m => int.Parse(m.Value)).ToArray();
    
    0 讨论(0)
  • 2020-11-22 04:02

    You can do this using String property like below:

     return new String(input.Where(Char.IsDigit).ToArray()); 
    

    which gives only number from string.

    0 讨论(0)
提交回复
热议问题