Reputation: 1609
8654 -> 8653; 1000 -> 0999; 0100 -> 0099; 0024 -> 0023; 0010 -> 0009; 0007 -> 0006 etc.
I have a string variable of fixed length 4; its characters are always numbers. I want to make subtraction while obeying the given rule that its length of 4 must be protected.
What I tried: Convert.ToInt32, .Length operations etc. In my code, I always faced some sort of errors.
I devised that I can do this via 3 steps:
1. Convert the string value to an (int) integer
2. Subtract "1" in that integer to find a new integer
3. Add "4 - length of new integer" times "0" to the beginning.
Anyway, independent of the plotted solution above (since I am a newbee; perhaps even my thought may divert a standard user from a normal plausible approach for solution), is not there a way to perform the above via a function or something else in C#?
Upvotes: 1
Views: 1375
Reputation: 59258
Well, I think others have implemented what you have implemented already. The reason might be that you didn't post your code. But none of the answers addresses your main question...
Your approach is totally fine. To make it reusable, you need to put it into a method. A method can look like this:
private string SubtractOnePreserveLength(string originalNumber)
{
// 1. Convert the string value to an (int) integer
// 2. Subtract "1" in that integer to find a new integer
// 3. Add "4 - length of new integer" times "0" to the beginning.
return <result of step 3 >;
}
You can then use the method like this:
string result = SubtractOnePreserveLength("0100");
// result is 0099
Upvotes: 1
Reputation: 127543
Your steps are almost right, however there is a easier way to accomplish getting the leading 0's, use Numeric string formatting. Using the formatting string "D4"
it will behave exactly like you want.
var oldString = "1000";
var oldNum = Convert.ToInt32(oldString);
var newNum = oldNum - 1;
var newString = newNum.ToString("D4");
Console.WriteLine(newString); //prints "0999"
You could also use the custom formatting string "0000"
.
Upvotes: 4
Reputation: 21887
A number doesn't have a format, it's string representation has a format.
The steps you outlined for performing the arithmetic and outputting the result are correct. I would suggest using PadLeft
to output the result in the desired format:
int myInt = int.Parse("0100");
myInt = myInt - 1;
string output = myInt.ToString().PadLeft(4, '0');
//Will output 0099
Upvotes: 4