Is there a better way to write the following method?
Is there a better, more elegant solu开发者_JAVA技巧tion to the following method?
Expected input format:
8 h 13 m
Expected output format:
8.13
My code:
private string FormatHours(string value)
{
//Example: (Input = 10 h 53 m) (Output = 10.53)
var timeValues = Regex.Split(value, @"[\shm]", RegexOptions.IgnoreCase).Where(s => !string.IsNullOrEmpty(s)).ToArray();
return ((timeValues != null) && (timeValues.Length == 2)) ? string.Format(@"{0:hh}.{1:mm}", timeValues[0], timeValues[1]) : null;
}
Is there a reason not to use the following?
value.Replace(" h ",".").Replace(" m",string.Empty)
I think Regex.Split
is overkill here. Regular old Match
will give you exactly what you want:
private static string FormatHours(string value)
{
Match m = Regex.Match(value, @"^(?<hours>\d{1,2}) h (?<minutes>\d{1,2}) m$");
if (m.Success)
{
int hours = int.Parse(m.Groups["hours"].Value);
int minutes = int.Parse(m.Groups["minutes"].Value);
if (hours >= 0 && hours < 24 && minutes >= 0 && minutes < 60)
return string.Concat(hours, ".", minutes);
}
return null;
}
The only thing I could think of is that if timeValues
was null
calling ToArray()
would throw
private string FormatHours(string value)
{
var timeValues = Regex.Split(value, @"[\shm]", RegexOptions.IgnoreCase).Where(s => !string.IsNullOrEmpty(s));
if (timeValues == null || timeValues.Count() != 2)
return null;
string[] arr = timeValues.ToArray();
return string.Format(@"{0:hh}.{1:mm}", arr[0], arr[1]);
}
Expression:
^(\d{1,2}) h (\d{1,2}) m$
Code:
var input = "8 h 13 m";
var regex = new Regex(@"^(\d{1,2}) h (\d{1,2}) m$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
var match = regex.Match(input);
if (!match.Success) throw new Exception();
int h = Int32.Parse(match.Groups[1].Value);
int m = Int32.Parse(match.Groups[2].Value);
var output = String.Format("{0}.{1}", h, m);
// or to be sure that that's the realistic numbers
var today = DateTime.Now;
var output2 = new DateTime(today.Year, today.Month, today.Day, h, m, 0).ToString("hh.mm");
LINQ is not really suited for you problem. Using regular expressions in a slightly different manner than you are doing is what I would do:
String FormatHours(String value) {
var regex = new Regex(@"^(?<hours>\d{1,2})\s*h\s*(?<minutes>\d{1,2})\s*m$");
var match = regex.Match(value);
if (match.Success) {
var hours = Int32.Parse(match.Groups["hours"].Value);
var minutes = Int32.Parse(match.Groups["minutes"].Value);
if (hours < 24 && minutes < 60)
return hours + "." + minutes;
}
return null;
}
You can adjust the regular expression to suit your exact needs. This one accepts strings like 10 h 53 m
and 10h53m
.
精彩评论