C
C#12mo ago
Radio

✅ List gets weird numbers

c#
string example = "9d4f1";
List<int> ints = new List<int>();

foreach (char c in example)
{
if (Char.IsDigit(c))
{
if (ints.Count != 2) ints.Add(c);
else ints[1] = c;
}
}

foreach (var item in ints) Console.WriteLine(item);
c#
string example = "9d4f1";
List<int> ints = new List<int>();

foreach (char c in example)
{
if (Char.IsDigit(c))
{
if (ints.Count != 2) ints.Add(c);
else ints[1] = c;
}
}

foreach (var item in ints) Console.WriteLine(item);
I was hoping for this to take the first int and the last int, yes there are probably better ways to do this but I am new to c# and want to come up with my own solutions. Atm if I run this code then "ints[0]" comes out as 57 (should be 9) and "ints[1]" comes out as 49 (should be 1) my idea was that it first uses the Add function to add 2 indexes (0 = the first number) then if it found more numbers then 2 if would just replace the last index (1). If anyone know why the values come out as they do, any help would be much appreciated
7 Replies
Thinker
Thinker12mo ago
Firstly: we have an #advent-of-code if you want more specific help with AoC catsip chars are kinda weird, because they're actually ints. When you do ints.Add(c), what it does is that it converts the char into the numerical code for the character, not the digit represented by the character.
MODiX
MODiX12mo ago
Thinker
REPL Result: Success
(int)'9'
(int)'9'
Result: int
57
57
Compile: 202.277ms | Execution: 21.727ms | React with ❌ to remove this embed.
Thinker
Thinker12mo ago
There are two things you can do here: you can use char.GetNumericValue(c) to get the numerical value of the character, or you can do the slightly hackier thing of c - '0'. Since '0' is actually an integer, you can subtract it from any other character to get the actual numeric value of the character, since if you subtract '0' from '0' then you'll get 0, '0' from '1' you'll get 1, and so on.
Pobiega
Pobiega12mo ago
int and char are not entirely the same oops, was scrolled up Thinker said what I wanted to say
Radio
RadioOP12mo ago
Alright, that makes sense, ty for the help, is there a way to put the post as solved, or do I just leave it there?
Thinker
Thinker12mo ago
$close
MODiX
MODiX12mo ago
Use the /close command to mark a forum thread as answered
Want results from more Discord servers?
Add your server