Split string at position in C #

I have a date stamp (020920111422) and I want to split it into

day = 02, month = 09, year = 2011, hour = 14, and minute = 22

Is there a "split string at position" method in C #?

+6
source share
6 answers

Do you want to:

string x = s.Substring(0, i), y = s.Substring(i); 

(or maybe i-1 / i + 1 depending on your exact requirements).

However, you can also use DateTime.ParseExact to load it into DateTime , specifying an explicit format:

 var when = DateTime.ParseExact("020920111422", "ddMMyyyyHHmm", CultureInfo.InvariantCulture); 
+13
source

you can do it via SubString - for example:

 string myDay = mydatestamp.SubString (0,2); 

OR create a DateTime :

 DateTime myDateTime = DateTime.ParseExact ( mydatestamp, "ddMMyyyyHHmm" , CultureInfo.InvariantCulture ); 
+6
source

When answering the question, considering "line splitting in position", you can use the String.Substring (Int32, Int32) method, calling several times at different offsets.

Also take a look at LINQ Take () and Skip () , which also allows you to return the number of elements.

Otherwise, see examples that are provided to other guys using DateTime.ParseExact(), I believe this is the most correct way to convert the string you provided to a DateTime value.

+3
source

You can also use

  var d = DateTime.Parse(s, "ddMMyyyyHHmm"); 

if the end goal is a DateTime.

+3
source

Instead, you can convert the date stamp using Datatime.ParseExact and you can extract the day, month, year, hour, and minute that you want from this date stamp. See the next part of the code for converting Datetime.ParseExact .

 DateTime.ParseExact(YourDate, "ddMMyyyyHHmm", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None) 
+2
source

For more information, maybe this will help.

 string rawData = "LOAD:DETAIL 11.00.0023.02.201614:52:00NGD ..."; var idx = 0; Func<int, string> read = count => { var result = rawData.Substring(idx, count);//.Trim(); idx += count; return result; }; var type = read(16); var version = read(8); var date = read(18); var site = read(8); //... 
0
source

Source: https://habr.com/ru/post/897133/


All Articles