C# split 20 digit numbers and assign it to 5 string variables - c#

I need guide as to how I can split 20 digit numbers (e.g 77772222666611118888) and uniquely assign to five declared int variables e.g int n1,n2,n3,n4,n5.
Expected result
int mynumber = 77772222666611118888;
And, after the splitting and assigning, one gets the following:
n1=7777;
n2=2222;
n3=6666;
n4=1111;
n5=8888;
Thanks

You can use a simple regex for it
string mynumber = "77772222666611118888";
var ns = Regex.Matches(mynumber, #"\d{4}").Cast<Match>()
.Select(x => x.Value)
.ToList();

If you need to use separate variables, you could do this:
string mynumber = "77772222666611118888";
string n1 = mynumber.Substring(0, 4);
string n2 = mynumber.Substring(4, 4);
string n3 = mynumber.Substring(8, 4);
string n4 = mynumber.Substring(12, 4);
string n5 = mynumber.Substring(16, 4);
If you're willing to use an array or another collection, you could do this:
int stringSize = 4;
string[] n = new string[mynumber.Length / stringSize];
for (int i = 0; i < n.Length; i ++)
{
n[i] = mynumber.Substring(i*4, stringSize);
}

You'll need a long or Decimal to store the initial number, as its too long for an int.
Once that is done, use modulus to get the digits (in reverse), and division to get rid of the used numbers:
long tempNumber = number;
List<long> splitNumbers = new List<long>();
while (tempNumber > 0)
{
long currentDigits = number % 10000;
tempNumber = tempNumber / 10000; //Make sure this is integer division!
//Store cuurentDigits off in your variables
// 8888 would be the first number returned in this loop
// then 1111 and so on
splitNumbers.Add(currentDigits);
}
//We got the numbers backwards, so reverse the list
IEnumerable<long> finalNumberList = splitNumbers.Reverse();
You could also turn it into a string, and use .Take(4) and int.Parse to get your numbers.

You should convert myNumber to a string first,
then extract each part of this number using the substring function
and parse those strings back to the desired integers

You haven't defined what the rules are for performing the split you asked about. Are you splitting based on position and length? Are you splitting based on runs of identical digits?
Assuming you're splitting based on runs of identical digits, you could use a backreference like so,
Regex rxSameDigits = new Regex(#"(\d)(\1)*") ;
The \1 says, use the value of the specified group, in this case, the group starting with the first left parenthesis in the regex. So it says to
Match any digit, followed by
zero or more of the exact same digit
So it will match sequences like 1, 22, 333, etc. So you can simply say:
string s = "1223334444555556666667777777888888889999999990000000000" ;
string[] split = rxSameDigits.Matches(s).Cast<Match>().Select( x => x.Value ).ToArray() ;
And get the expected
1
22
333
4444
55555
666666
7777777
88888888
999999999
0000000000

Related

How to take digits from two different numbers and form a new one

I have the following problem here:My input is several lines of 2 digit numbers and I need to make a new number using the second digit of the first number and the first of the next one.
Example:
int linesOfNumbers = Convert.ToInt32(Console.ReadLine());
for(int i = 0,i<linesOfNumbers,i++)
{
int numbers = Conver.ToInt32(Console.ReadLine());
//that's for reading the input
}
I know how to separate the numbers into digits.My question is how to merge them.
For example if your input is 12 and 21 the output should be 22.
I like oRole's answer, but I think they're missing a couple things with the example input that you provided in your comment. I'll also point out some of the errors in the code that you have.
First off, if you're only given the input 12,23,34,45, then you don't need to call Console.ReadLine within your for loop. You've already gotten the input, you don't need to get any more (from what you've described).
Secondly, unless you're doing mathematical operations, there is no need to store numerical data as ints, keep it as a string, especially in this case. (What I mean is that you don't store Zip Codes in a database as a number, you store it as a string.)
Now, onto the code. You had the right way to get your data:
var listOfNumbers = Console.ReadLine();
At that point, listOfNumbers is equal to "12,23,34,45". If you iterate on that variable as a string, you'll be taking each individual character, including the commas. To get each of the numbers to operate on, you'll need to use string.Split.
var numbers = listOfNumbers.Split(',');
This turns that list into four different two character numbers (in string form). Now, you can iterate over them, but you don't need to worry about converting them to numbers as you're operating on the characters in each string. Also, you'll need a results collection to put everything into.
var results = new List<string>();
// Instead of the regular "i < numbers.Length", we want to skip the last.
for (var i = 0; i < numbers.Length - 1; i++)
{
var first = numbers[i];
var second = numbers[i + 1]; // This is why we skip the last.
results.Add(first[1] + second[0]);
}
Now your results is a collection of the numbers "22", "33", and "44". To get those back into a single string, you can use the helper method string.Join.
Console.WriteLine(string.Join(",", results));
You could use the string-method .Substring(..) to achieve what you want.
If you want to keep int-conversion in combination with user input, you could do:
int numA = 23;
int numB = 34;
int resultAB = Convert.ToInt16(numA.ToString().Substring(1, 1) + numB.ToString().Substring(0, 1));
Another option would be to take the users input as string values and to convert them afterwards like that:
string numC = "12";
string numD = "21";
int resultCD = Convert.ToInt16(numC.Substring(1, 1) + numD.Substring(0, 1));
I hope this code snippet will help you combining your numbers. The modulo operator (%) means: 53 / 10 = 5 Rest 3
This example shows the computation of the numbers 34 and 12
int firstNumber = 34 - (34 % 10) // firstNumber = 30
int secondNumber = 12 % 10; // secondNumber = 2
int combined = firstNumber + secondNumber; // combined = 32
EDIT (added reading and ouput code):
boolean reading = true;
List<int> numbers = new ArrayList();
while(reading)
{
try
{
int number = Convert.ToInt32(Console.ReadLine());
if (number > 9 && number < 100) numbers.Add(number);
else reading = false; // leave reading process if no 2-digit-number
}
catch (Exception ex)
{
// leave reading process by typing a character instead of a number;
reading = false;
}
}
if (numbers.Count() > 1)
{
List<int> combined = new ArrayList();
for (int i = 1; i <= numbers.Count(); i++)
{
combined.Add((numbers[i-1] % 10) + (numbers[i] - (numbers[i] % 10)));
}
//Logging output:
foreach (int combination in combined) Console.WriteLine(combination);
}
As you mention, if you already have both numbers, and they are always valid two digit integers, following code should work for you.
var num1 = 12;
var num2 = 22;
var result = (num2 / 10)*10 + (num1 % 10);
num2/10 returns the first digit of second number, and num1 % 10 returns the second digit of the first number.
The % and / signs are your savior.
If you want the 'ones' digit of a number (lets call it X), simply do X%10 - the remainder will be whatever number is in the 'ones' digit. (23%10=3)
If, instead, the number is two digits and you want the 'tens' digit, divide it by ten. (19/10=1).
To merge them, multiply the number you want to be in the 'tens' digit by ten, and add the other number to it (2*10+2=22)
There are other solutions like substring, etc and many one have already given it above. I am giving the solution VIA LINQ, note that this isn't efficient and it's recommended only for learning purpose here
int numA = 12;
int numB = 21 ;
string secondPartofNumA = numA.ToString().Select(q => new string(q,1)).ToArray()[1]; // first digit
string firstPartofNumB = numB.ToString().Select(q => new string(q,1)).ToArray()[0]; // second digit
string resultAsString = secondPartofNumA + firstPartofNumB;
int resultAsInt = Convert.ToInt32(resultAsString);
Console.WriteLine(resultAsString);
Console.WriteLine(resultAsInt);

How to get count of numbers in int and how to split a number without making a string

I have a number like 601511616
If all number's length is multiple of 3, how can a split the number into an array without making a string
Also, how can I count numbers in the int without making a string?
Edit: Is there a way to simply split the number, knowing it's always in a multiple of 3... good output should look like this: {616,511,601}
You can use i % 10 in order to get the last digit of integer.
Then, you can use division by 10 for removing the last digit.
1234567 % 10 = 7
1234567 / 10 = 123456
Here is the code sample:
int value = 601511616;
List<int> digits = new List<int>();
while (value > 0)
{
digits.Add(value % 10);
value /= 10;
}
// digits is [6,1,6,1,1,5,1,0,6] now
digits.Reverse(); // Values has been inserted from least significant to the most
// digits is [6,0,1,5,1,1,6,1,6] now
Console.WriteLine("Count of digits: {0}", digits.Count); // Outputs "9"
for (int i = 0; i < digits.Count; i++) // Outputs "601,511,616"
{
Console.Write("{0}", digits[i]);
if (i > 0 && i % 3 == 0) Console.Write(","); // Insert comma after every 3 digits
}
IDEOne working demonstration of List and division approach.
Actually, if you don't need to split it up but only need to output in 3-digit groups, then there is a very convenient and proper way to do this with formatting.
It will work as well :)
int value = 601511616;
Console.WriteLine("{0:N0}", value); // 601,511,616
Console.WriteLine("{0:N2}", value); // 601,511,616.00
IDEOne working demonstration of formatting approach.
I can't understand your question regarding how to split a number into an array without making a string - sorry. But I can understand the question about getting the count of numbers in an int.
Here's your answer to that question.
Math.Floor(Math.Log10(601511616) + 1) = 9
Edit:
Here's the answer to your first question..
var n = 601511616;
var nArray = new int[3];
for (int i = 0, numMod = n; i < 3; numMod /= 1000, i++)
nArray[i] = numMod%1000;
Please keep in mind there's no safety in this operation.
Edit#3
Still not perfect, but a better example.
var n = 601511616;
var nLength = (int)Math.Floor(Math.Log10(n) + 1)/ 3;
var nArray = new int[nLength];
for (int i = 0, numMod = n; i < nLength; numMod /= 1000, i++)
nArray[i] = numMod%1000;
Edit#3:
IDEOne example http://ideone.com/SSz3Ni
the output is exactly as the edit approved by the poster suggested.
{ 616, 511, 601 }
Using Log10 to calculate the number of digits is easy, but it involves floating-point operations which is very slow and sometimes incorrect due to rounding errors. You can use this way without calculating the value size first. It doesn't care if the number of digits is a multiple of 3 or not.
int value = 601511616;
List<int> list = new List<int>();
while (value > 0) // main part to split the number
{
int t = value % 1000;
value /= 1000;
list.Add(t);
}
// Convert back to an array only if it's necessary, otherwise use List<T> directly
int[] splitted = list.ToArray();
This will store the splitted numbers in reverse order, i.e. 601511616 will become {616, 511, 601}. If you want the numbers in original order, simply iterate the array backwards. Alternatively use Array.Reverse or a Stack
Since you already know they are in multiples of 3, you can just use the extracting each digit method but use 1000 instead of 10. Here is the example
a = 601511616
b = []
while(a):
b.append(a%1000)
a = a//1000
print(b)
#[616, 511, 601]

Finding number of digits of a number in C#

I'm trying to write a piece of code in C# to find the number digits of a integer number, the code works perfectly for all numbers (negative and positive) but I have problem with 10, 100,1000 and so on, it shows one less digits than the numbers' actual number of digits. like 1 for 10 and 2 for 100..
long i = 0;
double n;
Console.Write("N? ");
n = Convert.ToInt64(Console.ReadLine());
do
{
n = n / 10;
i++;
}
while(Math.Abs(n) > 1);
Console.WriteLine(i);
Your while condition is Math.Abs(n) > 1, but in the case of 10, you are only greater than 1 the first time. You could change this check to be >=1 and that should fix your problem.
do
{
n = n / 10;
i++;
}
while(Math.Abs(n) >= 1);
Use char.IsDigit:
string input = Console.ReadLine();
int numOfDigits = input.Count(char.IsDigit);
What's wrong with:
Math.Abs(n).ToString(NumberFormatInfo.InvariantInfo).Length;
Indeed, converting a number to a string is computationally expensive compared to some arithmetic, but it is hard to deal with negative nubers, overflow,...
You need to use Math.Abs to make sure the sign is not counted, and it is a safe option to use NumberFormatInfo.InvariantInfo so that for instance certain cultures that use spaces and accents, do not alter the behavior.
public static int NumDigits(int value, double #base)
{
if(#base == 1 || #base <= 0 || value == 0)
{
throw new Exception();
}
double rawlog = Math.Log(Math.Abs(value), #base);
return rawlog - (rawlog % 1);
}
This NumDigits function is designed to find the number of digits for a value in any base. It also includes error handling for invalid input. The # with the base variable is to make it a verbatim variable (because base is a keyword).
Console.ReadLine().Replace(",", String.Empty).Length;
this will count all the char in a string
int amount = 0;
string input = Console.ReadLine();
char[] chars = input.ToArray();
foreach (char c in chars)
{
amount++;
}
Console.WriteLine(amount.ToString());
Console.ReadKey();

C# char calculation problem

Im trying to do a permutation. of five in this case, so 5,4,3,2,1 . Eventually I want it to permute up to 100 which can be stored in my intX class. the calculation is fine, but I want to add up all individual numbers of the output, using the script below.
so 5! = 5x4x3x2x1 = 120 ----> 1+2+0 = 3. BUT My script below gives the output 147:
120
1
2
0
147
What am I doing wrong? I allready tried all converts, I started with just using the string[pointer] thingy, I tried different arrays etc.. but it all keeps coming up with 147. Is it some kind of representation thing?
static void Main(string[] args)
{
IntX total=1;
IntX totalsum = 0;
int perm = 5;
for (int i = perm; i > 0; i--)
{
total = total * i;
}
Console.WriteLine(total);
string answerstring = Convert.ToString(total);
char[] answerArray = answerstring.ToArray();
for (int x = 0; x < answerArray.Length; x++)
{
totalsum += Convert.ToInt32(answerArray[x]);
Console.WriteLine(answerArray[x]);
}
Console.WriteLine(totalsum);
}
The problem is the way you are converting your answerArray elements back to numbers
Convert.ToInt32(answerArray[x])
The above line takes the char 1 and converts it to an int. This is not the same as parsing it as an int. 1 is ascii character 49 so internally the char has an int representation of 49 and so that is what it is converted to (since this is just trying to do a type conversion rather than any kind of processing)
Similarly 2 = 50 and 0 = 48 so you get the total of 147.
What you want to do is use Integer.Parse to parse strings as numbers. I believe it should implicitly convert the char to a string before parsing it.
So your loop would be:
for (int x = 0; x < answerArray.Length; x++)
{
totalsum += int.Parse(answerArray[x].ToString());
Console.WriteLine(answerArray[x]);
}
You can also do it the way others suggested with subtracting chars. This works because the ascii value of 1 is 1 higher than the ascii value for 0. 2 is 2 higher, etc.
Of course this only works with single digit chars. If you ever want to convert more than two digit numbers into int from a string you'll need int.parse.
For what its worth I suspect that the character subtraction method is the most efficient since it is effectively just doing some very simple type conversion and subtraction. The parse method is likely to do a lot more stuff and so be a bit more heavyweight. I dont' you will notice a performance difference though.
The problem lies in here:
for (int x = 0; x < answerArray.Length; x++)
{
//Casting char to int, not what you want!
//totalsum += Convert.ToInt32(answerArray[x]);
//Parsing char to int, what you do want!
totalsum += int.Parse(answerArray[x]);
Console.WriteLine(answerArray[x]);
}
Instead of converting to an integer (which will take the ASCII character value), try using answerArray[x] - '0'.
(int)'0' is not equal to 0. You should use ((int)answerArray[x] - (int)'0')
Why bother changing it to a char array? You already have the information that you need.
while (total > 0)
{
ones_digit = total % 10;
totalsum += ones_digit;
total -= ones_digit;
total /= 10;
}
Convert.ToInt32 returns the Unicode values of characters 1, 2 and 0 which are 49, 50 and 48. That's why the sum comes out as 147.

How can I count the numbers in a string of mixed text/numbers

So what I'm trying to do, is take a job number, which looks like this xxx123432, and count the digits in the entry, but not the letters. I want to then assign the number of numbers to a variable, and use that variable to provide a check against the job numbers to determine if they are in a valid format.
I've already figured out how to perform the check, but I have no clue how to go about counting the numbers in the job number.
Thanks so much for your help.
Using LINQ :
var count = jobId.Count(x => Char.IsDigit(x));
or
var count = jobId.Count(Char.IsDigit);
int x = "xxx123432".Count(c => Char.IsNumber(c)); // 6
or
int x = "xxx123432".Count(c => Char.IsDigit(c)); // 6
The difference between these two methods see at Char.IsDigit and Char.IsNumber.
Something like this maybe?
string jobId = "xxx123432";
int digitsCount = 0;
foreach(char c in jobId)
{
if(Char.IsDigit(c))
digitsCount++;
}
And you could use LINQ, like this:
string jobId = "xxx123432";
int digitsCount = jobId.Count(c => char.IsDigit(c));
string str = "t12X234";
var reversed = str.Reverse().ToArray();
int digits = 0;
while (digits < str.Length &&
Char.IsDigit(reversed[digits])) digits++;
int num = Convert.ToInt32(str.Substring(str.Length - digits));
This gives num 234 as output if that is what you need.
The other linq/lambda variants just count characters which I think is not completely correct if you have a string like "B2B_MESSAGE_12344", because it would count the 2 in B2B.
But I'm not sure if I understood correctly what number of numbers means. Is it the count of numbers (other answers) or the number that numbers form (this answer).

Categories