C# increment a variable and convert to string on one line [duplicate] - c#

This question already has answers here:
Pre- & Post Increment in C#
(6 answers)
Closed 5 years ago.
Simple request -- does anybody know a way to consolidate this to one line:
edit - I was NOT confused about pre vs post increment operators. The question I posted should have worked, I honestly do not know what happened. somewhere between VS and SO I fixed it.
startingMask++;
string mask2 = startingMask.ToString().PadLeft(3, '0');
Something like
string mask2 = (startingMask++).ToString().PadLeft(3, '0');
edit -- Alright -- chill out -- :)
Here is the final full solution, I should have provided more info in my first question, I was just looking for a nudge in the right direction (the number needed and starting number will be changing via a database pull at some point):
int startingMask = 76;
int numberNumberNeeded = 10;
List<string> masks = new List<string>();
while (numberNumberNeeded > 0)
{
string newMask = (startingMask++).ToString().PadLeft(3, '0');
masks.Add(newMask);
numberNumberNeeded--;
}

string mask2 = (++startingMask).ToString().PadLeft(3, '0');
Postfix ++ startingMask++ first take value and then increment value
Sufix ++ ++startingMask first increment value and then take value

Related

Correct way to change value in List<int> / array [duplicate]

This question already has answers here:
i = i++ doesn't increment i. Why? [duplicate]
(4 answers)
Closed 1 year ago.
Suppose the List/array
List<int> a = new List<int>(){1,2,3,4,5};
int []a = new int[]{1,2,3,4,5};
And I want to change the value at index 2, whats the correct way?
a[2]++; or a[2] = a[2]++;
Please explain the answer.
The result of a[2] = a[2]++ will be a[2], in this case 3.
The postfix increment a[2]++ will change the value of a[2] after the line in which it appears has finished.
If you want to change the value, then a[2]++ or a[2] = ++a[2] are valid.
The correct way is the first one:
A[2]++;
The second one also works but it does more work than necessary. It is equivalent to the following code:
a[2] = a[2]; // useless
a[2]++;
The suffix ++ operator (as in x++) applies after the line in which it appears has finished executing. The prefix ++ operator (as in ++x) first modifies the element and then uses the value.
I suggest you read the documentation about the "increment operator":
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#increment-operator-

C# Edit existing value on a specific line in a text file [duplicate]

This question already has answers here:
Edit a specific Line of a Text File in C#
(6 answers)
Closed 3 years ago.
I'm making a small game and I'm having trouble saving the result of the game into a text file.
I have tried reading only the needed line but with little success:
List<string> a = File.ReadLines(path).Skip(2).Take(2).ToList();
Text file has 4 lines inside it:
PlayerTag
Wins: 0
Losses: 0
Draws: 0
After the player wins I want increase the amount of wins by 1.
What would be the ideal way to do this?
With the current format, you could do the following.
var str = File.ReadAllLines(filePath);
str[WinPosition] = Update(str[WinPosition]);
File.WriteAllLines(filePath);
Where WinPosition is a constant defined as
const int WinPosition = 1;
const int LossesPosition = 2;
const int DrawsPosition = 3;
And Update is defined as
private string Update(string source)
{
var data = source.Split(':');
data[1] = (Int32.Parse(data[1])+1).ToString();
return string.Join(":",data);
}
The Update method would read the string, split it based on the delimiter (":") and then update the numeric part. Together, the constants and common update method would allow you to update Losses and Draws in the same way as Wins (and perhaps more readable than using 1/2/3 indices directly).
str[LossesPosition] = Update(str[LossesPosition]);
str[Draws] = Update(str[Draws]);
Having said so, If you have the option changing the format of the file, I would suggest you opt for Json or Xml. This would be a better approach than using the current format.

lambda functions have strange behaviors in loops, how to fix? [duplicate]

This question already has answers here:
Can someone explain "access to modified closure" in C# in simple terms? [duplicate]
(1 answer)
Captured variable in a loop in C#
(10 answers)
Closed 5 years ago.
I get a really weird behavior with this piece of code
for (int i = 0; i < 2; ++i)
optionContent.GetChild(i).GetComponent<Button>().onClick.AddListener(() => SetOption(i, true));
The weird behavior is that all listeners gets attached the function SetOption(2, true)
I think the 2 comes from the fact that at the end of the for loop, i is set to 2, but still, why is this the behavior and is there a way to get around this?
Edit:
I played around for a bit and I think the problem is that delegates store variable references as references, not values
int x = 0;
Action a = delegate { int b = x; Console.WriteLine(b); };
x = 10;
a();
The above code will print 10, instead of 0. How do I make it to use the value 0?

Float calculation showing difference. Positive showing negative? [duplicate]

This question already has answers here:
Always return positive value
(9 answers)
Closed 5 years ago.
I am calculating the difference between two numbers. If the calculation ends up being 5 - 10, it equals to "-5". If this is the case I need results to display/equal to "+5" , with the "+" sign.
I basically need reverse. So same if 10 - 5 quals to "5" I need it to display as "+5"
Code below I am using:
float rowresults = ROW1 - ROW2;
Textbox.text = rowresults.ToString();
Math.Abs is what you are looking for:
float rowresults = Math.Abs(ROW1 - ROW2);
And to add the "+"-sign to the front of the text (without changing your elsewise existing behaviour):
Textbox.text = "+" + rowresults.ToString();

Regular expression to match numbers between 1-5000 [duplicate]

This question already has answers here:
Using regular expressions to validate a numeric range
(11 answers)
Closed 2 years ago.
I would like to use a regex for a textbox that allows only numbers between 1-5000
I've tried the following but it wont work:
#"/^(?:1|5000|-[1-9]\d?)$/
You can use ^(?:[1-9]|\d{2,3}|[1-4]\d{3}|5000)$. But you'd better to parse to Int then do simple maths.
With some parsing beforehand, you can make the regex very simple:
string s = textBox1.Text;
string r = "";
int n = 0;
if (int.TryParse(s, out n) && (n>=1 && n<=5000))
{
r = "y";
}
if (Regex.IsMatch(r, "y")) {
// input was valid
MessageBox.Show("OK");
}
Try ...
^(?:[1-4][0-9]{1,3}|[1-9][0-9]{0,2}|5000)$
You can do something like the following:
^(([1-4][0-9]{0,3})|([1-9][0-9]{0,2})|(5000))$
The first two groups will match anything in the range of 1 - 4999. You add the |5000 at the end to make it match the range 1 - 5000. The three cases here are:
The number is exactly 5000
The number is between 1 and 3 digits. In this case, it can't possibly be more than 5000. However, the first number must be 1 - 9 so that you can't get something like "009" or "000."
The number is 4 digits, in which case it must be between 1000 - 4999
With that said, I think it would probably be simpler to just parse the int and see if it's in range.
You can try something like this (0-366)
^(0?[0-9]?[0-9]|[1-2][0-9][0-9]|3[0-5][0-9]|36[0-6])$

Categories