【发布时间】:2015-02-08 14:59:40
【问题描述】:
我想获取字符串中数字的第一个实例。
所以我得到了这个输入字符串,它可能是以下之一:
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.
编辑:很多人发布了很好的解决方案,但我最终接受了我在代码中实际使用的解决方案。我希望我能接受更多的答案!
【问题讨论】:
标签: c# string numbers substring