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

Get int[] result like this int[0] <- 123 , int[1] <- 456 , int[2] <- 789

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

Get int[] result like this int[0] <- 111, int[1] <- 222 , int[2] <- 333

How to do it !?

1
  • 2
    You could extract all sequences of digits from the string using Regex.Matches(str, @"\d+") Commented Jan 14, 2022 at 7:16

2 Answers 2

4

You can try regular expressions in order to match all items:

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

...

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

If array items must have 3 digits only, change [0-9]+ pattern into [0-9]{3}

Sign up to request clarification or add additional context in comments.

2 Comments

You don't need the Cast, although maybe it depends on .net version.
@Yuriy Faktorovich: older .Net versions require Cast<Match> (or OfType<Match>) since their MatchCollection doesn't implement IEnumerable<Match>
2

Just to demonstrate what @Klaus Gütter suggests, and with linq:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.