首页 > 解决方案 > 使用 .Split 拆分字符串并返回第一个整数值(不使用 LINQ)

问题描述

我可以使用 Linq 来做到这一点,但我很难做到这一点,如果可能的话,我更喜欢没有:

带有 LINQ 的代码:

        string result = sentencewithint
                .Split("")
                .FirstOrDefault(item => Regex.IsMatch(item, @"^\-?[0-9]+$"));

        int firstint = int.Parse(result);

        return firstint;

标签: c#linq

解决方案


您可以使用regex

string sentencewithint = "1567438absdg345";
string result = Regex.Match(sentencewithint, @"^\d+").ToString();
Console.WriteLine(result); //1567438

或者TakeWhile仅当它们是数字时才使用扩展方法从条件中的字符串中获取字符

string sentencewithint = "1567438absdg345";
string num = new String(sentencewithint.TakeWhile(Char.IsDigit).ToArray());  
Console.WriteLine(result); //1567438

推荐阅读