简体   繁体   English

如何解析,实际上从 c# 中的字符串中获取数字?

[英]How to parse, actually get number from string in c#?

I am trying to get only part with number.我试图只获得数字的一部分。 For example in input could be just number like 50, or string like: 50 and more.例如,输入可能只是数字,如 50,或字符串,如:50 或更多。 Also Number always will be on first place.数字也总是排在第一位。 And I want always to get only number from that.我总是想从中得到唯一的数字。 I tried like this, but this does not work:我试过这样,但这不起作用:

double presureTendency;

var presureTendencyToString= Convert.ToString(presureTendency.ToString());
var presureTendencySplited = presureTendencyToString.Split(' ');
var pressureTendencyNumber = presureTendencySplited[0];

You can extract the number from the string using a regular expression.您可以使用正则表达式从字符串中提取数字。 See an example below.请参阅下面的示例。 One thing to pay an attention to are your locale settings as they influence the format of the double.需要注意的一件事是您的语言环境设置,因为它们会影响双精度的格式。

string pattern = @"^\d+\.\d+";
string input = "50.1 , or more";
Match m = Regex.Match(input, pattern, RegexOptions.IgnoreCase);
if (m.Success) {
    double nr = Double.Parse(m.Value);
    Console.WriteLine(nr);
}

So if i enter "507.89foo123,456bah" you want only 507 or you want 507.89?因此,如果我输入“507.89foo123,456bah”,您只需要 507 还是需要 507.89?

Please read, I write 50, not 50 with coma or something decimal.请阅读,我写的是 50,而不是 50 昏迷或小数。 I just want 507 in your example我只想在你的例子中使用 507


Well, then it's pretty easy:那么,这很容易:

string input = "50.1 , or more";
char[] digits = input.TakeWhile(Char.IsDigit).ToArray();
if(digits.Any())
{
    string result = new string(digits); // "50"
    // if you want an integer:
    int number = int.Parse(result); 
}

If only want the number at the beginning of the string you can do it by simply parsing the initial value and ignoring the rest, since, judging from your comments, you don't have decimal separators it's even simpler:如果只想要字符串开头的数字,您可以通过简单地解析初始值并忽略 rest 来做到这一点,因为从您的评论来看,您没有小数分隔符,它更简单:

var myString = Console.ReadLine().Trim(' '); // read console input
                                             // trim spaces
var numericString = new List<char>();

foreach (var c in myString)
{
    if (char.IsDigit(c))
    {
        numericString.Add(c); // if is digit parse
    }
    else
    {
        break; // the first non digit breaks the cycle
    }
}

// parse the value as int
if (int.TryParse(numericString.ToArray(), out var myVal))
{
    Console.WriteLine(myVal);
}

Live demo现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM