从字符串结尾垃圾解析整数整数、字符串、结尾、垃圾

2023-09-03 01:26:46 作者:看到此昵称的都是萌比

我需要分析一个十进制整数出现在一个字符串的开始。

可能有尾随垃圾以下的十进制数。这需要被忽略(即使它包含其它数目。)

例如。

 1=> 1
42=> 42
3 -.X.-=> 3
2 3 4 5=> 2
 

有一个内置的方式在.NET框架来做到这一点?

int.TryParse()是不适合的。它允许尾随空格而不是其他尾随字符。

这将是很容易实现这一点,但我想preFER如果存在使用标准方法。

解决方案

 的foreach(VAR在Regex.Matches M(3  -  .X 4,@\ D +) )
{
    Console.WriteLine(米);
}
 

每秒更新注释

不知道为什么你不喜欢经常EX pressions,所以我就寄我觉得是最短的解决方案。

牛客网 C C 工程师能力评估 20选择题

要获得第一INT:

 匹配匹配= Regex.Match(3  -  .X  -  4,@\ D +);
如果(match.Success)
    Console.WriteLine(int.Parse(match.Value));
 

I need to parse a decimal integer that appears at the start of a string.

There may be trailing garbage following the decimal number. This needs to be ignored (even if it contains other numbers.)

e.g.

"1" => 1
" 42 " => 42
" 3 -.X.-" => 3
" 2 3 4 5" => 2

Is there a built-in method in the .NET framework to do this?

int.TryParse() is not suitable. It allows trailing spaces but not other trailing characters.

It would be quite easy to implement this but I would prefer to use the standard method if it exists.

解决方案

foreach (var m in Regex.Matches(" 3 - .x. 4", @"\d+"))
{
    Console.WriteLine(m);
}

Updated per comments

Not sure why you don't like regular expressions, so I'll just post what I think is the shortest solution.

To get first int:

Match match = Regex.Match(" 3 - .x. - 4", @"\d+");
if (match.Success)
    Console.WriteLine(int.Parse(match.Value));