我想要在一个字符串中找到第一个数字的实例。
因此,我有了这个输入字符串,它可能是以下之一:
1: "Event: 1 - Some event"
2: "Event 12 -"
3: "Event: 123"
4: "Event: 12 - Some event 3"
输入字符串的输出必须是:
1: 1
2: 12
3: 123
4: 12
我已经尝试了以下几种方法,但是没有一种可以完全满足我的要求。
number = new String(input.ToCharArray().Where(c => Char.IsDigit(c)).ToArray());
//This gives me all the numbers in the string
var index = input.IndexOfAny("0123456789".ToCharArray());
string substring = input.Substring(index, 4);
number = new string(substring.TakeWhile(char.IsDigit).ToArray());
//This gives me first number and then the numbers in the next 4 characters. However it breaks if there is less than 4 characters after the first number.
编辑:很多人发表了好的解决方案,但我最终接受了我在代码中实际使用的那个。我希望我能接受更多的答案!