Home > front end >  (c#)How do I split a string in 2 with a colon in?
(c#)How do I split a string in 2 with a colon in?

Time:02-01

Problem:

I have a textbox with an entry field, in which a user inputs time in a 00:00 format (HH:mm). What I would like to do is extract 2 integers from the string, the Hours (20:00 = 20 hours) and the minutes (00:20 = 20 minutes).

I've tried looking into String.Split() method but I can't wrap my head around it and how to apply it to my problem. Can anyone give me some advice on this?

Thanks

CodePudding user response:

Extending my comment into an answer. It seems like you're about to parse a string into a time which you can achieve with TimeSpan class and extract needed informations easily. For that you need to know what format your time input is and how you want to process it. Judging by your code I can assume you always expect a format of hh:mm which indicates that first part is an hour in 2 digit format ( either 02:mm or 14:mm ), same with minutes. This alone solves most of your problems because you can just parse your string into TimeSpan using ParseExact method:

// first, create a format you want to be used
const string FORMAT = "hh:mm";

// now just use TimeSpan.ParseExact method to retrieve your data
var result = TimeSpan.ParseExact(YourTextBoxText, FORMAT);

This will return a TimeSpan which has properties like Hours, Minutes etc. which you can then use to retrieve whatever time value you want.


EDIT: Things to note are that the above can throw a bunch of exceptions depending on the data input, formats etc. It's up to you if you're about to make any custom logic based on exception or whatever. Exceptions you might need to include in your logic and be aware of are

  • ArgumentNullException - thrown whenever argument is null,
  • FormatException - thrown whenever text input is in invalid format

For more info about TimeSpan you shold refer to the documentation

CodePudding user response:

You could use the TimeSpan.Parse() function to convert the string to a TimeSpan. Not the fastest method, but it's clean.

string time = "20:20";
if (TimeSpan.TryParse(time, out TimeSpan timespan))
{
    // Do something with:
    // timespan.Hours
    // timespan.Minutes
}

CodePudding user response:

You can split the input string with the : character. The first part is the hour and the second part is the minute

string s= "20:00";
var tempArray = s.Split(':');
int H = int.Parse(tempArray[0]);
int M = int.Parse(tempArray[1]);
  • Related