I have some c# code like this:
string myString = "20180426";
I know how to parse around specific characters (using the string.Split thing), but how do I get it to return 3 strings like this:
2018
04
26
I have several strings that are formatted this way ("YYYYMMDD"), so I don't want code that will only work for this specific string. I tried using
var finNum = myString[0] + myString[1] + myString[2] + myString[3];
Console.Write(finNum);
But I guess it's treating the characters as integers, rather than a text string because it's doing some mathematical operation with them instead of concatenating (it's not addition either because it's returning 203, which isn't the sum of 2, 0, 1 and 8).
I've tried changing var to string, but it won't let me implicitly convert int to string. Why does it think that string myString is an int, rather than a string, which is what I declared it as?
I could also use DateTime.Parse and DateTime.ParseExact, but apparently "20180426" isn't recognized as a valid DateTime:
DateTime myDate = DateTime.ParseExact(myString, "YYYYMMDD", null);
Console.WriteLine(myDate);
Thank you for your help. I know the answer is probably stupidly easy and I feel dumb for asking but I seriously checked all over various websites and can't find a solution that works for my issue here.
yyyyMMdd.YYYYandDDare not recognized as valid format characters, they are treated as string literalsvar finNum = myString[0] + myString[1] + (...) ;sums the ASCII values of the corresponding chars. If you add a string transformation (you need to use it just on the first char):var finNum = myString[0].ToString() + myString[1] + (...) ;it will switch to string concatenation.var finNum = myString[0] + myString[1] + myString[2] + myString[3];-myString[1]returns a character - if you try to do mathical operations with a char it will calculate the integer representation of the char so yourvar finNumis actually anintas you can see here: dotnetfiddle.net/tP9nRU