TnD_Guy
TnD_Guy

Reputation: 113

How to parse string into an array using set number of characters in C#

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.

Upvotes: 0

Views: 102

Answers (2)

HiramL.
HiramL.

Reputation: 3

If you want year, month and day separated by variables you could try:

       string mystring = "20180426";
       mystring = mystring.Insert(4,"-");
       mystring = mystring.Insert(7,"-");

       string year = mystring.Split('-')[0];
       string month = mystring.Split('-')[1];
       string day = mystring.Split('-')[2];
  1. First I add a character "-" to separate year and month, then another to separate month and day. You get something like "2018-04-26"

  2. Then I split the string and save the position 0 that store the first 4 numbers of your string into a variable named year.

Good luck!

Upvotes: -1

Tim Schmelter
Tim Schmelter

Reputation: 460148

I could also use DateTime.Parse and DateTime.ParseExact, but apparently "20180426" isn't recognized as a valid DateTime.

Yes, because the format string YYYYMMDD is incorrect, years and days are lowercase:

DateTime myDate = DateTime.ParseExact(myString, "yyyyMMdd", null);

If you want the year, month and day:

int year = myDate.Year;
int month = myDate.Month;
int day = myDate.Day;

Upvotes: 3

Related Questions