使用.Split拆分字符串并返回第一个整数值(不带LINQ)



我可以使用Linq来完成这项工作,但我很难在没有的情况下完成,如果可能的话,我更喜欢没有:

带LINQ的代码:

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

您可以使用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

您可以放置简单循环而不是Linq

foreach (string item in sentencewithint.Split(""))
if (Regex.IsMatch(item, @"^-?[0-9]+$"))
return int.Parse(item);
//TODO: Put some default value here (in case no item has been matched)
return -1;

.Split不是Linq方法。您正在使用的唯一Linq是FirstOrDefault。但为了回答您的问题,所有的.Net都是开源的,所以您可以查找源代码并复制它。

这是FirstOrDefault的源代码。你可以这样写你自己的FirstOrDefaultMethod

public static TSource? FirstOrDefault<TSource>(this IEnumerable<TSource> source) =>
source.TryGetFirst(out _);
private static TSource? TryGetFirst<TSource>(this IEnumerable<TSource> source, out bool found)
{
if (source == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}
if (source is IPartition<TSource> partition)
{
return partition.TryGetFirst(out found);
}
if (source is IList<TSource> list)
{
if (list.Count > 0)
{
found = true;
return list[0];
}
}
else
{
using (IEnumerator<TSource> e = source.GetEnumerator())
{
if (e.MoveNext())
{
found = true;
return e.Current;
}
}
}
found = false;
return default;
}

这里是string的源代码,它包括第975行的Split

最新更新