c# - 使用 .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
推荐阅读
- javascript - 使用 React-Multi-Carousel 反应轮播
- c++ - 仅在少数方法(静态或共享库)中未解析的外部符号
- c - opencv 程序中的错误:输入参数的大小不匹配
- visual-studio - 在 VS Studio 中找不到构建运行器
- bash - ssh 客户端自动填充子网的别名
- python - 使用python从图像中删除CT床
- c - 我不明白为什么我不能像这样在最后添加一个节点
- project-reactor - 如何监控 Flux.onBackpressureBuffer() 队列大小
- npm - 如何在没有双破折号的情况下将参数传递给 NPM 脚本
- javascript - 为什么只有最后一个元素显示数组而不是 JavaScript 中的所有元素