Nerdynosaur
Nerdynosaur

Reputation: 1888

Splitting numeric string into array

I have the string(10325710) and I want to split the string into an array. After I split the string into an array, the array will be {1,0,3,2,5,7,1,0}. Note there are two 1s and two 0s in the string. I don't want to split the '1' and the '0'. Therefore, the array I wish to get is {10,3,2,5,7,10}.

Any advice?

my C# code:

string myNumber = "10325710";
string[] myArray = myNumber.Select(p => p.ToString()).ToArray();

Upvotes: 3

Views: 481

Answers (4)

Eren Ersönmez
Eren Ersönmez

Reputation: 39085

int[] nums = myNumber.Replace("10", "A")
                     .Select(c => Convert.ToInt32(c.ToString(), 16))
                     .ToArray();

Basically replacing "10"s with "A"s, and then treating each character as a base-16 number.

Upvotes: 16

Spook
Spook

Reputation: 25927

You can do it manually quite easily.

int i = 0;

int len = 0;
for (int j = 0; j < s.Length; j++)
    if (s[j] != '0')
        len++;

int[] result = new int[len];
int index = 0;
while (i < s.Length)
{
    if (i < s.Length - 1 && int.Parse(s[i + 1].ToString()) == 0)
    {
        result[index++] = int.Parse(s[i].ToString()) * 10;
        i += 2;
    }
    else
    {
        result[index++] = int.Parse(s[i].ToString());
        i++;
    }
}

return result;

Upvotes: 1

Ken Kin
Ken Kin

Reputation: 4693

statement:

var myArray=Regex.Matches(myNumber, @"1?\d").Cast<Match>().Select(p => p.ToString()).ToArray();

code:

var myNumber="98765432101032571001210345610789";
var myMatches=Regex.Matches(myNumber, @"1?\d").Cast<Match>();
var myArray=myMatches.Select(p => p.ToString()).ToArray();

var whats_in_myArray="{ "+String.Join(", ", myArray)+" }";
Debug.Print("{0}", whats_in_myArray);

output:

{ 9, 8, 7, 6, 5, 4, 3, 2, 10, 10, 3, 2, 5, 7, 10, 0, 12, 10, 3, 4, 5, 6, 10, 7, 8, 9 }

Upvotes: 1

sloth
sloth

Reputation: 101052

Well, just to put some regex on the table:

Regex.Split(myNumber, @"(?!^)(?=[1-9])");

Upvotes: 4

Related Questions