从字符串中获取 int 数组

Get int array from string

string str = "XXX_123_456_789_ABC";
int[] intAry = GetIntAryByStr(str);

这样得到int[] resultint[0] <- 123 , int[1] <- 456 , int[2] <- 789

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

这样得到int[] resultint[0] <- 111, int[1] <- 222 , int[2] <- 333

怎么做!?

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

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}

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

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