String formats

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hey,

Can someone help me to find a short and effective way to do the follow.

I have
Number1 as integer = 234
Number2 as integer = 5645

I want to create a string as follows (it is an obligatoire format for the
banks):
+++123/4567/89012+++

My example :
Number1 I want to present in a 5 char string, but left aligned with 0
Number 2 the same

as follows : 0023405645
from that int I have to calculate the MODULO 97 = 30

Now the string must be in following format
+++002/3405/64530+++

I looked in regex but don't find a good way to do it.

Thanks for help.
jac
 
The problem with terse and tricky solutions is that you have to come
back later and figure out what you did and why it works. Personally, I
prefer the boring solution, even if it is long-winded. It's easier to
understand both now and in the future:

long compositeNumber = number1 * 10000L + number2;
long checkSum = compositeNumber % 97;
string compositeString = compositeNumber.ToString().PadLeft(10, '0');
string checkSumString = checkSum.ToString().PadLeft(2, '0');
string bankString = String.Format("+++{0}/{1}/{2}{3}+++",
compositeString .Substring(0, 3), compositeString .Substring(3, 4),
compositeString .Substring(7), checkSumString);

As I said, boring, but it works and anyone who reads the code will
understand why it works. (Of course, you should comment it well to
indicate _why_ it does what it does! :)

By the way, you need the "long" data types because if number1 is
greater than 21473 then you risk having a compositeNumber that is
bigger than an int can hold. As well, this code does not guarantee that
the result will always be 20 characters long: if number1 or number2 is
greater than 99999 then the resulting string will be longer and
probably malformed. If either number is negative then the '-' will
appear in the middle of the bankString. You should check for this
before you start and throw an InvalidArgumentException if either number
is > 99999 or < 0.
 
Thank you Bruce.
I did it also the long way. But I forgot the Long (didn't think of that), i
used an simple int . Thanks of your answer.

Jac
 
Try this:

using System;
class App
{
static void Main(string[] args)
{
int n1 = 234;
int n2 = 5645;

string s1 = n1.ToString("00000");
string s2 = n2.ToString("00000");
int mod = int.Parse(s1+s2) % 97;

string res = String.Format("+++{0}/{1}{2}/{3}{4}+++",
s1.Substring(0,3), s1.Substring(3,2), s2.Substring(0,2),
s2.Substring(2,3), mod.ToString("00"));
Console.WriteLine(res);
}
}

Regards,
Joakim
 
Back
Top