Reputation: 749
I have a number something like this : 12345668788451223356456898941220036696897894
Now, the question is how can I split the number after each 8 digits.That is, I need the output as : 12345668
78845122 and so on up to the end of the number. If I convert it to string, I don't have a method so that I could split it only with length parameter.
Thanks in advance for answering.
Upvotes: 0
Views: 521
Reputation: 1502386
String approach
If I convert it to string, I don't have a method so that I could split it only with length parameter.
Well you have Substring
, don't you? You could use LINQ:
var numbers = Enumerable.Range(0, bigNumber.Length / 8)
.Select(x => bigNumber.Substring(x * 8, 8)
.ToList();
or a straight loop:
var numbers = new List<string>();
for (int i = 0; i < bigNumber.Length / 8; i++)
{
numbers.Add(bigNumber.Substring(i * 8, 8);
}
If you need to end up with a List<int>
instead, just add a call to int.Parse
in there.
(You should check that the input string length is a multiple of 8 first.)
BigInteger approach
It's not clear what form you have this number in to start with. If it's a BigInteger
, you could keep using DivRem
:
BigInteger value = ...;
List<BigInteger> results = new List<BigInteger>();
BigInteger divisor = 100000000L;
for (int i = 0; i < count; i++)
{
BigInteger tmp;
value = BigInteger.DivRem(value, divisor, out tmp);
results.Add(tmp);
}
Note that I'm using count
here rather than just looping until value
is 0, in case you have lots of leading 0s. You need to know how many numbers you're trying to extract :)
Upvotes: 4
Reputation: 237
Have you tried using
string string.substring(int startIndex,int length)
In you case, you can write a loop to extract the 8 digits from the string till all the numbers are extracted
string sDigits = "12345668788451223356456898941220036696897894";
int iArrLen = sDigits.length / 8;
string[] sArrDigitList = new string[iArrLen];
for(int i=0; i < sDigits.length; i++)
{
sArrDigitList[i] = sDigits.substring(0, 8);
sDigits = sDigits.substring(sDigits.length-8);
}
Upvotes: 0
Reputation: 18064
Use this regex to split after each 8 digits,
\d{1,8}
OR
(\d{1,8})
12345668
78845122
33564568
98941220
03669689
7894
Upvotes: 2