【问题标题】:Get int array from string从字符串中获取 int 数组
【发布时间】:2022-01-14 07:12:27
【问题描述】:
string str = "XXX_123_456_789_ABC";
int[] intAry = GetIntAryByStr(str);

像这样int[0] <- 123 , int[1] <- 456 , int[2] <- 789获取int[] result

string str = "A111B222C333.bytes";
int[] intAry = GetIntAryByStr(str);

像这样int[0] <- 111, int[1] <- 222 , int[2] <- 333获取int[] result

怎么做!?

【问题讨论】:

  • 您可以使用Regex.Matches(str, @"\d+")从字符串中提取所有数字序列

标签: c# string integer


【解决方案1】:

您可以尝试正则表达式以匹配所有项目:

using System.Linq;
using System.Text.RegularExpressions;

...

int[] intAry = Regex
  .Matches(str, "[0-9]+")
  .Cast<Match>()
  .Select(match => int.Parse(match.Value))
  .ToArray(); 

如果数组项必须只有3 数字,请将[0-9]+ 模式更改为[0-9]{3}

【讨论】:

  • 你不需要 Cast,虽然它可能取决于 .net 版本。
  • @Yuriy Faktorovich:较旧的 .Net 版本需要 Cast&lt;Match&gt;(或 OfType&lt;Match&gt;),因为它们的 MatchCollection 没有实现 IEnumerable&lt;Match&gt;
【解决方案2】:

只是为了演示@Klaus Gütter 的建议,并使用 linq:

        static int[] GetIntAryByStr(string s)
        {
            return Regex.Matches(s, @"\d+")
                .OfType<Match>()
                .Select(x => Convert.ToInt32(x.Value))
                .ToArray();
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-05
    • 2016-06-11
    • 2012-10-31
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    相关资源
    最近更新 更多